Javascript-форум (https://javascript.ru/forum/)
-   Events/DOM/Window (https://javascript.ru/forum/events/)
-   -   Как обернуть элемент без jQ (https://javascript.ru/forum/events/52622-kak-obernut-ehlement-bez-jq.html)

iyaki 27.12.2014 16:04

Как обернуть элемент без jQ
 
Интересует аналог, если можно так сказать функции WrapInner
есть див в нем часть текста в спанах и часть без, по мимо того валяеются ссылки и прочее. А нужно обернуть в спан одно слово "Куплю".

<div>
Куплю
<a id="thread_title_3384515" href="showthread.php?t=3384515">готовый бизнес или долевое участие</a>

<span class="smallfont" style="white-space:nowrap">
(
<img class="inlineimg" border="0" alt="Тема на нескольких страницах" src="http://static.kharkovforum.com/images/misc/multipage.gif" title="Тема на нескольких страницах">
<a href="showthread.php?t=3384515">1</a>
<a href="showthread.php?t=3384515&page=2">2</a>
)
</span>
</div>

krutoy 27.12.2014 16:16

<html>
<head>
<style>
.bar{background: grey}
</style>
</head>
<body>


<div>foo bar baz</div>


<script>
d=document.querySelector("div")
d.innerHTML=d.innerHTML.replace("bar", "<span class='bar'>bar</span>")

</script>
</body>
</html>

iyaki 27.12.2014 17:08

ППц! Спасибо! Пол дня промаялся оказывается точку провтыкал перед replase. TypeError: o.innerHTMLreplace is not a function

bes 28.12.2014 00:25

<style>
	.bar{background: grey}
</style>
<div>foo bar <button>baz</button></div>
<script>
document.querySelector("button").addEventListener("click", function () {
	alert("I'm baz");
});
setTimeout(function () {
	var d=document.querySelector("div")
	d.innerHTML=d.innerHTML.replace("bar", "<span class='bar'>bar</span>");
	alert("shut up, Mr. baz");
}, 3000);
</script>

bes 28.12.2014 10:04

the first attempt
<style>
.bar {
	background: grey;
}
</style>
<div>foo bar rar <button>baz</button></div>
<script>
document.querySelector("button").addEventListener("click", function () {
	alert("I'm baz");
});

function wr(textNode, word, html) {
	var parent = textNode.parentNode,
		nodeValue = textNode.nodeValue,//data, wholeText
		pos = nodeValue.indexOf(word),
		fragment = document.createDocumentFragment(),
		el = document.createElement( html );
	
	el.classList.add("bar");
	el.innerHTML = word;
	fragment.appendChild( document.createTextNode( nodeValue.substr(0, pos) ) );
	fragment.appendChild( el );
	fragment.appendChild( document.createTextNode( nodeValue.substr( pos + word.length ) ) );
	parent.insertBefore(fragment, textNode);
	parent.removeChild(textNode);
}

setTimeout(function () {
	wr(document.querySelector("div").firstChild, "bar", "span");
	alert("hello, Mr. baz");
}, 3000);
</script>

kaflan 03.01.2015 04:59

Вредные советы, от Ильи почитайте) там много такого)


Часовой пояс GMT +3, время: 20:47.