I have an array of strings with DOMs in it such as:
array = [
"<p >text</p>",
"<h1>hello</h1>
];
I want to replace the content of each DOMs, I wanted to use the replace() method but since it's not always <p>
and sometimes the DOM got a class, I can't just target the text between <p>
and </p>
. I tried to use the .html()
method on the array item but it's not working. Do you have any idea?
CodePudding user response:
Here you go.
var array = [
"<p class='item'>text</p>",
"<h1>hello</h1>"
];
$.each(array, function(index, val) {
var $str = $(val);
if ($str.hasClass("item")) {
$str.addClass("new").removeClass("item");
console.log($str.attr('class'));
} else
console.log($str.html()) // if needed change your HTML here with condition
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
CodePudding user response:
Try this:
let array = [
"<p class='item'>a lot of text</p>",
"<h1>hello</h1>"
]
function changeElementText(_array, _index, _newText) {
return _array.map((e, i) => {
if (i === _index) return e.replace(/>[\s\S]*</g, `>${_newText}<`)
return e
})
}
console.log(changeElementText(array, 0, 'Text Changed!