I am trying to select one ore more elements that are NOT descendants of another specific element.
<html>
<body>
<div>
<p>
<b>
<i> don't select me </i>
</b>
</p>
</div>
<div>
<i>don't select me either </i>
</div>
<i> select me </i>
<b>
<i> select me too </i>
</b>
</body>
</html>
In the example above I want to select all 'i' elements, that are not inside div elements.
The other way around would be easy, with ('div i'), but using this in :not() is not possible.
How can I select all i elements outside of div elements?
Often it is suggested the use of jQuery, which would be like:
nondiv_i = all_i.not(all_div.find("i"))
I can't use jQuery, but could use jqLite - jqLite does not have a not()-function. A jqLite solution is welcome too!
Is it possible to do this without repeated iterations and comparisons?
Edit: To clarify, i don't want to have any div-ancestors for my i-elements, not only no direct div-parents.
A comparable XPath would look like this:
//i[not(ancestor::div)]
function isDescendant(parent, child) {
var all = parent.getElementsByTagName(child.tagName);
for (var i = -1, l = all.length; ++i < l;) {
if(all[i]==child){
return true;
}
}
return false;
}
for the specific case of yours;
is = document.getElementsByTagName("i");
divs = document.getElementsByTagName("div");
nondivs = [];
var contains;
for(i=0;i<is.length;i++){
contains = false;
for(j=0;j<divs.length;j++){
if(isDescendant(divs[j],is[i])){
contains = true;
j = divs.length;
}
}
if(!contains){
nondivs.push(is[i]);
}
}
Add a class to all of the <i> tags ("itag", for example). From there, you can fetch them by calling getElementsByClassName:
var r = document.getElementsByClassName("itag");
console.log("length" + r.length);
You can then get them by index:
console.log(r[0]);
console.log(r[1].innerHTML); // get text of i tag
Related
I've got following HTML:
<span class="testClass1" >
wanted Text
<a class="ctx" href="#"></a>
</span>
Now I want to get the text "wanted Text".
How can I achieve this?
I tried with:
document.getElementsByClassName("testClass1");
I also tried with document.getElementsByTagName() but I don't know how to use them properly.
You can use querySelectorAll
hence:
document.querySelectorAll('.testclass1 a')
will return all the <a> items children of a .testclass1
Snippet example:
var elements = document.querySelectorAll('.testClass1 a')
console.log(elements) // open the console to see this
console.log(elements[0].text) // this gets the first <a> text `wanted Text`
<span class="testClass1" >
wanted Text
<a class="ctx" href="#"></a>
</span>
The getElementsByClassName() function returns an array of matching elements, so if you need to access them, you could do so using a loop :
// Get each of the elements that have the class "testClass1"
var elements = document.getElementsByClassName("testClass1");
// Iterate through each element that was found
for(var e = 0; e < elements.length; e++){
// Get the inner content via the innerHTML property
var content = elements[e].innerHTML;
}
If you need to actually access the <a> tags directly below some of the elements as your edit indicates, then you could potentially search for those wihtin each of your existing elements using the getElementsbyTagName() function :
// Get each of the elements that have the class "testClass1"
var elements = document.getElementsByClassName("testClass1");
// Iterate through each element that was found
for(var e = 0; e < elements.length; e++){
// Find the <a> elements below this element
var aElements = elements[e].getElementsByTagName('a');
// Iterate through them
for(var a = 0; a < aElements.length; a++){
// Access your element content through aElements[a].innerHTML here
}
}
You can also use an approach like squint's comment or Fred's which take advantage of the querySelectorAll() function as the getElementsByClassName() and getElementsByTagName() are better served when accessing multiple elements instead of one specifically.
Try this:
document.getElementsByClassName("testClass1")[0].getElementsByTagName('a')[0].innerText
var testClass1 = document.getElementsByClassName("testClass1");
console.log(testClass1[0].innerHTML);
This question already has answers here:
javascript variable corresponds to DOM element with the same ID [duplicate]
(3 answers)
Closed 9 years ago.
I have multiple spans
<span id ="myId">data1</span>
<span id ="myId">data2</span>
<span id ="myId">data3</span>
<span id ="myId">data4</span>
<span id ="myId">data5</span>
I want to delete text inside all span on single button click.
I tried this on button click in javascript
document.getElementById("myId").innerHTML = "";
but it is removing text from only 1st span
IDs are unique, Classes are repeatable
The purpose of an id in HTML is to identify a unique element on the page. If you want to apply similar styles or use similar scripts on multiple elements, use a class instead:
<span class="myClass">data1</span>
<span class="myClass">data2</span>
<span class="myClass">data3</span>
<span class="myClass">data4</span>
<span class="myClass">data5</span>
<input type="button" id="clearbutton" value="Clear Data">
Now let's remove the text
Now, you can select all of these elements and set their text to anything you want. This example uses jQuery, which I recommend because older versions of IE don't support getElementsByClassName:
$('#clearbutton').click(function() {
$('.myClass').text('');
});
Link to Working Demo | Link to jQuery
Or in Vanilla JS
If you're not worried about supporting IE, you can do this with vanilla JavaScript:
function clearSpans() {
var spans = document.getElementsByClassName("myClass");
for(var i=0; i < spans.length; i++) ele[i].innerHTML='';
}
Link to Working Demo
Note: You can add getElementsByClassName to IE
I wouldn't recommend doing this because it's simpler and more widely accepted to just use jQuery, but there have been attempts to support older IEs for this function:
onload=function(){
if (document.getElementsByClassName == undefined) {
document.getElementsByClassName = function(className)
{
var hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
var allElements = document.getElementsByTagName("*");
var results = [];
var element;
for (var i = 0; (element = allElements[i]) != null; i++) {
var elementClass = element.className;
if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass))
results.push(element);
}
return results;
}
}
}
Link to source
Dont give same ID to more than one one tag, use class instead
<span class ="myId">data1</span>
<span class ="myId">data2</span>
<span class ="myId">data3</span>
<span class ="myId">data4</span>
<span class ="myId">data5</span>
call this function to clear
function clearAll()
{
var ele= document.getElementsByClassName("myId");
for(var i=0;i<ele.length;i++)
{
ele[i].innerHTML='';
}
}
You are using a DOM method that relies to the DOM of ID, that is, per DOM, there can only be one element with the same ID.
However, you do not use the id attribute that way in your HTML, so instead you are looking for the selector to query all elements with the id myId, you perhaps know it from CSS:
document.querySelectorAll("#myId").innerHTML = '';
This does not work out of the box, you also need to add the innerHTML setter to the NodeList prototype, but that is easy:
Object.defineProperty(NodeList.prototype, "innerHTML", {
set: function (html) {
for (var i = 0; i < this.length; ++i) {
this[i].innerHTML = html;
}
}
});
You find the online demo here: http://jsfiddle.net/Pj4HD/
var spans=document.getElementsByTagName("span");
for(var i=0;i<spans.length;i++){
if(spans[i].id=="myId"){
spans[i].innerHTML="";
}
}
Although I suggest you don't keep same IDs
http://jsfiddle.net/YysRp/
im trying to get an article from a div, and the problem is it gets everything when i use $('#article').html() is there a way for just getting a spesific html inside the parent div without other elements?
<div id="article">
This is an article
blabla
<br/>
<b>something bold here</b>
<div id="unknown">{some javscript}</div>
<link type="anything" url="somewhere">
<style>
.something
</style>
the end of the article
</div>
should return
this is an article
blabla
<br/>
<b>something bold here</b>
the end of the article
See http://jsfiddle.net/TULKC/
var el=document.getElementById('article'),
text=getText(el);
function getText(el){
var els=el.childNodes,
t='';
for(var i=0;i<els.length;i++){
if(els[i].nodeType==3){//If it's a text node
if(!/^\s+$/.test(els[i].nodeValue)){//We avoid spaces
t+=els[i].nodeValue;
}
}else if(els[i].nodeType==1){//If it's an element node
var nName=els[i].nodeName.toLowerCase(),
c=check(nName);
if(c==1){//Allowed elements
t+='<'+nName+'>'+getText(els[i])+'</'+nName+'>';
}else if(c==2){//Allowed self-closing elements
t+='<'+nName+' />';
}
}
}
return t;
}
function check(nodeName){
switch(nodeName){
case 'b': return 1;//Allowed elements
case 'br':return 2;//Allowed self-closing elements
default:return 0;
}
}
alert(text);
Note: You can add more exceptions this way:
switch(nodeName){
case 'b': case 'a': return 1;//Allowed elements
case 'br':case 'img':return 2;//Allowed self-closing elements
default:return 0;
}
(Well, if you use HTML5, img is not a self-closing element)
Edit:
If you want to keep the attributes, you can use the following function
function getAttr(el){
var attr=el.attributes,
t='';
for(var i=0;i<attr.length;i++){
t+=' '+attr[i].nodeName+'="'+attr[i].nodeValue+'"';
}
return t;
}
and then
if(c==1){
t+='<'+nName+getAttr(els[i])+'>'+getText(els[i])+'</'+nName+'>';
}else if(c==2){
t+='<'+nName+getAttr(els[i])+' />';
}
See it here: http://jsfiddle.net/TULKC/4/
Something like this should get you what you want I guess:
(function($) {
$article = $('#article').clone();
$('div, link, style', $article).remove();
console.log($article.html());
})(jQuery);
Demo: http://jsfiddle.net/EQ7zC/
You can use innerText or .text() in jQuery to get all text without tags, including the text in childs.
Also, if you need to get only the text in parent div, without the text of child elements, you can iterate it's child nodes, and check if it is text node.
Something like this:
var innerText = "";
$('#yourDiv').each(function(){
var $cn = this.childNodes;
for (var i = 0, l = $cn && $cn.length || 0; i < l; i++) {
if ($cn[i].nodeType == 3 && String($cn[i].nodeValue).split(/\s/).join('')) {
innerText += $cn[i].nodeValue;
}
}
});
console.log(innerText);
is this a possibility ?
<div id="article">
<a>This is an article -- a starts article
blabla
<br/>
<b>something bold here</b>
</a> -- /a ends article
<div id="unknown">{some javscript}</div>
<link type="anything" url="somewhere">
<style>
.something
</style>
the end of the article
$('#article').find('a').html();
I have many spans with the same ID. how can assign their values to different variables in order of their occurance.
Ex
<span id="hello"> 18</span>
<span id="hello"> 12</span>
<span id="hello"> 21</span>
I want var1 = 18 var2= 12 var3= 21
See my comment regarding IDs. Now assuming you give that elements a class hello instead, this will work in all browsers:
var values = [],
spans = document.getElementsByTagName('span');
for(var i = 0, l = spans.length; i < l; i++) {
var span = spans[i];
if(span.className === 'hello') {
values.push(span.innerHTML);
}
}
DEMO
If you can't change the HTML, in this case you can compare the IDs:
if(span.id === 'hello')
This is ok, because we are iterating over all spans. But methods like getElementById won't work!
The id tag is supposed to be unique within a document. If you are trying to give them the same style, then you should use the class attribute instead of the id attribute. You can use the jQuery class selector to get all elements with a given class (assuming you change to using class instead of id).
Can you please tell me if there is any DOM API which search for an element with given attribute name and attribute value:
Something like:
doc.findElementByAttribute("myAttribute", "aValue");
Modern browsers support native querySelectorAll so you can do:
document.querySelectorAll('[data-foo="value"]');
https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll
Details about browser compatibility:
http://quirksmode.org/dom/core/#t14
http://caniuse.com/queryselector
You can use jQuery to support obsolete browsers (IE9 and older):
$('[data-foo="value"]');
Update: In the past few years the landscape has changed drastically. You can now reliably use querySelector and querySelectorAll, see Wojtek's answer for how to do this.
There's no need for a jQuery dependency now. If you're using jQuery, great...if you're not, you need not rely it on just for selecting elements by attributes anymore.
There's not a very short way to do this in vanilla javascript, but there are some solutions available.
You do something like this, looping through elements and checking the attribute
If a library like jQuery is an option, you can do it a bit easier, like this:
$("[myAttribute=value]")
If the value isn't a valid CSS identifier (it has spaces or punctuation in it, etc.), you need quotes around the value (they can be single or double):
$("[myAttribute='my value']")
You can also do start-with, ends-with, contains, etc...there are several options for the attribute selector.
We can use attribute selector in DOM by using document.querySelector() and document.querySelectorAll() methods.
for yours:
document.querySelector("[myAttribute='aValue']");
and by using querySelectorAll():
document.querySelectorAll("[myAttribute='aValue']");
In querySelector() and querySelectorAll() methods we can select objects as we select in "CSS".
More about "CSS" attribute selectors in https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
FindByAttributeValue("Attribute-Name", "Attribute-Value");
p.s. if you know exact element-type, you add 3rd parameter (i.e.div, a, p ...etc...):
FindByAttributeValue("Attribute-Name", "Attribute-Value", "div");
but at first, define this function:
function FindByAttributeValue(attribute, value, element_type) {
element_type = element_type || "*";
var All = document.getElementsByTagName(element_type);
for (var i = 0; i < All.length; i++) {
if (All[i].getAttribute(attribute) == value) { return All[i]; }
}
}
p.s. updated per comments recommendations.
Use query selectors, examples:
document.querySelectorAll(' input[name], [id|=view], [class~=button] ')
input[name] Inputs elements with name property.
[id|=view] Elements with id that start with view-.
[class~=button] Elements with the button class.
Here's how you can select using querySelector:
document.querySelector("tagName[attributeName='attributeValue']")
Here is an example , How to search images in a document by src attribute :
document.querySelectorAll("img[src='https://pbs.twimg.com/profile_images/........jpg']");
you could use getAttribute:
var p = document.getElementById("p");
var alignP = p.getAttribute("align");
https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute
Amendment for Daniel De León's Answer
It's possible to search with
^= - filters Elements where id (or any other attr) starts with view keyword
document.querySelectorAll("[id^='view']")
very simple, try this
<!DOCTYPE html>
<html>
<body>
<h1>The Document Object</h1>
<h2>The querySelector() Method</h2>
<h3>Add a background color to the first p element:</h3>
<p>This is a p element.</p>
<p data-vid="1">This is a p element.</p>
<p data-vid="2">This is a p element.</p>
<p data-vid="3">This is a p element.</p>
<script>
document.querySelector("p[data-vid='1']").style.backgroundColor = "red";
document.querySelector("p[data-vid='2']").style.backgroundColor = "pink";
document.querySelector("p[data-vid='3']").style.backgroundColor = "blue";
</script>
</body>
</html>
function optCount(tagId, tagName, attr, attrval) {
inputs = document.getElementById(tagId).getElementsByTagName(tagName);
if (inputs) {
var reqInputs = [];
inputsCount = inputs.length;
for (i = 0; i < inputsCount; i++) {
atts = inputs[i].attributes;
var attsCount = atts.length;
for (j = 0; j < attsCount; j++) {
if (atts[j].nodeName == attr && atts[j].nodeValue == attrval) {
reqInputs.push(atts[j].nodeName);
}
}
}
}
else {
alert("no such specified tags present");
}
return reqInputs.length;
}//optcount function closed
This is a function which is is used tu to select a particular tag with specific attribute value. The parameters to be passed are are the tag ID, then the tag name - inside that tag ID, and the attribute and fourth the attribute value.
This function will return the number of elements found with the specified attribute and its value.
You can modify it according to you.