[英]Find DOM element in text content using javascript
Please push me towards a duplicate of this question if possible. 如果可能的话,请把我逼到这个问题的重复项。 I've looked everywhere but can't seem to find it.
我到处都看过,但似乎找不到。
How do I do a getElementById on text content? 如何对文本内容执行getElementById?
var test = '<div id="thisDiv">HI</div>';
How do I select thisDiv if it's not a part of the DOM? 如果它不是DOM的一部分,如何选择thisDiv?
Create an element, set your string as its innerHTML
and then search inside that ... 创建一个元素,将您的字符串设置为其
innerHTML
,然后在其中搜索...
Something like 就像是
var test = '<div id="thisDiv">HI</div>';
var element = document.createElement('DIV');
element.innerHTML = test;
alert(element.textContent);
( changed the initial outerHTML
as you can only maintain a reference to the originaly created element, and not the new one that is created by the new html ) ( 更改了最初的
outerHTML
因为您只能维护对原始创建的元素的引用,而不是对由新html创建的新元素的引用 )
For getting the text value inside your tags, use RegEx: 要在标签内获取文本值,请使用RegEx:
var re = new RegExp("<(.|\n)*?>", "g");
var content = test.replace(re,"");
You could create a temporary DIV and populate it with your string. 您可以创建一个临时DIV并用您的字符串填充它。 Even then, your ability to access it would be limited.
即使那样,您访问它的能力也会受到限制。 Add it to the DOM to access it using getElementById.
将其添加到DOM以使用getElementById访问它。
var div = document.createElement('div');
div.innerHTML = '<div id="thisDiv">HI</div>';
alert(div.firstChild);
To avoid creating that extra element, we could just add it to the body... 为了避免创建额外的元素,我们可以将其添加到主体中。
var test = '<div id="thisDiv">HI</div>';
document.querySelector('body').innerHTML = test;
console.log(document.getElementById('thisDiv'));
Getting just the text... 只是获取文字...
console.log(document.getElementById('thisDiv').textContent); // returns HI
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.