[英]Javascript search for tag and get it's innerHTML
It's probably something really simple, but I'm just learning. 这可能是非常简单的事情,但我只是在学习。
There's a page with 3 blockquote tags on it, and I'd need to get the innerHTML of the one containing a certain string. 有一个页面上有3个blockquote标签,我需要得到包含某个字符串的innerHTML。 I don't know how to search/match a string and get the innerHTML of the tag containing the matched result.
我不知道如何搜索/匹配字符串并获取包含匹配结果的标记的innerHTML。
Any help would be appreciated! 任何帮助,将不胜感激!
var searchString = 'The stuff in innerHTML';
var elements = document.getElementsByTagName('blockquote')
for (var i = 0; i < elements.length; i++) {
if (elements[i].innerHTML.indexOf(searchString) !== -1) {
alert('Match');
break;
}
}
:) :)
Btw there would be a much nicer method if you'd be using Prorotype JS (which is much better than jQuery btw): 顺便说一句,如果你使用Prorotype JS (比jQuery btw好得多)会有一个更好的方法:
var el = $$('blockquote').find(function(el) {
return el.innerHTML.indexOf('The string you are looking for.') !== -1;
});
You could of course also use regular expressions to find the string, which might be more useful (use el.match() for that). 您当然也可以使用正则表达式来查找字符串,这可能更有用(使用el.match())。
If you need to search through every <blockquote>
on the page, try this: 如果您需要搜索页面上的每个
<blockquote>
,请尝试以下操作:
function findBlockquoteContainingHtml(matchString) {
var blockquoteElements = document.getElementsByTagName('BLOCKQUOTE');
var i;
for (i = 0; i < blockquoteElements.length; i++) {
if (blockquoteElements[i].innerHTML.indexOf(matchString) >= 0) {
return blockquoteElements[i].innerHTML;
}
}
return null;
}
Assign an id to the blockquote elements then you can get the innerHTML like this: 为blockquote元素分配一个id然后你就可以像这样得到innerHTML:
HTML: HTML:
<blockquote id="bq1">Foo</blockquote>
JS: JS:
var quote1 = document.getElementById('bq1').innerHTML;
Be careful using innerHTML
to search for text within a tag, as that may also search for text in attributes or tags as well. 小心使用
innerHTML
搜索标记内的文本,因为它也可以搜索属性或标记中的文本。
You can find all blockquote
elements using: 您可以使用以下命令查找所有
blockquote
元素:
var elems = document.getElementsByTagName("blockquote")
You can then look through their innerHTML
, but I would recommend instead looking through their textContent
/ innerText
(sadly, this is not standardized across browser, it seems): 然后你可以查看他们的
innerHTML
,但我建议改为查看他们的textContent
/ innerText
(遗憾的是,这似乎没有跨浏览器标准化,似乎):
for (i in elems) {
var text = elems[i].textContent || elems[i].innerText;
if (text.match(/foo/)) {
alert(elems[i].innerHTML);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.