Iterate Over Every Element And Get Only The Content That Is Directly In The Node
let's assume I have this code
FirstLevelP SecondLevelSpan
FirstLevelP SecondLevelSpan Thi
Solution 1:
finding and changing text without child elements works this ways:
// search every element
$("body *").each(function(index, el) {
// find first text nodevar node = $(el).contents().filter(function() {
returnthis.nodeType === 3;
})[0];
// change text
node.textContent = "new text";
});
Solution 2:
Edit, Updated
Try
$("body *").each(function (i, el) {
if ($(el).is("p, span")) {
$(el).text(function (idx, text) {
var t = text.split("\n")[0];
// if `text` string's last character is not `.`// concat `.` to `text` string ,// return `text` original string's with `.` addedreturn t.slice(-1) !== "." ? t + "." : t
})
}
})
$("body *").each(function (i, el) {
if ($(el).is("p, span")) {
$(el).text(function (idx, text) {
var t = text.split("\n")[0];
return t.slice(-1) !== "." ? t + "." : t
})
}
})
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><p>FirstLevelP
<span>SecondLevelSpan</span></p><p>FirstLevelP
<span>SecondLevelSpan
<p>ThirdLevelP</p></span></p>
Post a Comment for "Iterate Over Every Element And Get Only The Content That Is Directly In The Node"