I need a solution to remove a div without an ID tag in JavaScript only. The div looks like this <div align="center">.
Here is the full structure.
<tr id="-1">
<td class="stxt">
<div align="center">
</div>
</td>
</tr>
You need to work out how to get a reference to it, once you've done that, you can remove it using:
div.parentNode.removeChild(div);
Of course the align attribute has been deprecated, but anyway, you can find the divs with align="center" using:
var divs = document.getElementsByTagName('div');
var div;
var i = divs.length;
while (i--) {
div = divs[i];
if (div.getAttribute('align') == 'center') {
div.parentNode.removeChild(div);
}
}
Which will remove every div in the document that has align="center".
Note that the object returned by getElementsByTagName is a NodeList. If you iterate over it from 0 and remove nodes, they are removed from the live list so you will skip the node following the one you remove and you will attempt to access no existant nodes at the end. Going over the list backwards avoids these pitfalls. An alternative is to turn the NodeList into an array, but that's somewhat inefficient.
Edit
Since you edited the question, here's an update answer.
You can get a reference to the TR using getElementById:
var root = document.getElementById('-1');
Now you can go down the DOM:
var cell = root.cells[0]; // First cell in the row
var div = cell.getElementsByTagName('div')[0]; // first div
cell.removeChild(div);
Which is specific to the structure you've posted.
If you can just remove the content, you can use:
var all = document.getElementsByTagName("div");
for(i=0; i < all.length; i++) {
all[i].innerHTML = ""
}
See http://jsfiddle.net/7KVkC/
You need some way to make this div tag unique. There is another javascipt function called getElementsByTagName that you can use to get an array of all of the div tags. You can then use the DOM to check whether that div tag has the property of align="center".
Related
As the API document declared:
If an element selected this way is inserted into a single location
elsewhere in the DOM, it will be moved into the target (not cloned).
Important: If there is more than one target element, however, cloned
copies of the inserted element will be created for each target except
for the last one.
var div = $("<div></div>").addClass("divCells"),
tdName = $("<td></td>").addClass("tdName"),
tdAge = $("<td></td>").addClass("tdAge"),
tdGender = $("<td></td>").addClass("tdGender"),
tds = [tdName, tdAge, tdGender],
tr = $("<tr></tr>"),
tbody = $("#peopleList tbody");
tds.append(div);
tr.append(tdName).append(tdAge).append(tdTimetdGenderstamp);
tbody.append(tr);
As above code represents, I try to include the 3 tds in to an Array, so that I could append div into all of them, but it is not working.
You're trying to use jQuery .append on a vanilla JavaScript Array. .append only works on jQuery/DOM elements, not JavaScript types such as Arrays.
Your tds array contains jQuery/DOM elements, but the Array itself isn't 'appendable' in the manner you're attempting.
Using an Array, you'll have to iterate through your array, and manually append the div to each element in it. Furthermore, since you will be appending to 3 separate elements individually (i.e. 1 per iteration, not all 3 at the same time) you'll have to manually .clone the div yourself, otherwise you'll just be appending the one div to the 1st item in the Array, and then moving the same div to the 2nd, and again to the 3rd. So...
// tds.append(div); // Change this to...
for (var i=0; i< tds.length; i++) {
tds[i].append(div.clone())
}
OR...
You could forget about using the Array altogether, and have jQuery clone and append the div for you (as your original question implied). Here's how...
// Remove the following lines...
// tds = [tdName, tdAge, tdGender],
// tds.append(div);
// Then, after you add the td's to your row here...
tr.append(tdName).append(tdAge).append(tdGender);
// ...have jQuery find all the td's and clone+append your div to them in one hit:
tr.find('td').append(div)
I need a method to clone say 4 div's with id's like d_1, d_2, d_3, d_4
including the contents inside each div all at once and then detach all divs, and then I need to find copy of d_1 and its contents from the clone and append it again to the page.
something like:
var cloned=$('[id^="d_"]').clone();
$('[id^="d_"]').detach();
and then find div with id =d_1 from clone and append it to body.
Is it possible?
Use Document Fragment.
var $documentFragment = $(document.createDocumentFragment());
$('[id^="d_"]').each(function(){
$documentFragment.append($(this).clone().addClass("_cloned"));
});
$documentFragment.clone().appendTo(document.body);
If you want looking for an element into the fragment, you can do this:
$(document.body).find("#d_1._cloned"). ... ;
If you want to remove all the element and then append only the first copied into fragment:
$("._cloned", document.body).remove();
$documentFragment.find("#d_1").clone().appendTo(document.body);
You can appendTo() an element to detach and move an element elsewhere.
var els = $('[id^="d_"]')
els.detach();
els.each(function() {
if (this.id.indexOf('d_1') !== -1) {
$(this).appendTo(document.body);
}
});
// do something else with els later, too.
I have an input button where is written within a blade foreach loop in a laravel project.
<div class="v-percentage">
<input id="copycode" type="Submit" value="Embed">
</div>
I am trying to write a script that will allow me to add a target attribute on the input so each button would be unique, and do something like this answer here. The script I wrote so far it should get the element and then within a for loop to add the target which i am not sure yet how I should do this.
var elements = document.getElementById('#copycode');
alert(elements);
for(var i = 0; i < elements.length; i++)
{
//add the target to the element
}
Also, when I alert the elements is returning null. How can i work that out?
document.getElementById('copycode')
getElementById just wants the ID, not a CSS selector.
Also, this will return one element (not a NodeList). IDs are unique throughout the page. If you want to select multiple elements, use classes and getElementsByClassName.
the Javascript function getElementById only returns one element. If you are trying to get a set of elements, try to use a class
<input class="copycode" type="submit" value="Embed" />
Then you could use a jquery selector to get the set of elements and iterate over then
$(".copycode").each(function(key, element){
element.attr("target", "foo");
});
If you don't want to use jquery, use the javascript function getElementsByClassName and a for to iterate over the set of elements
var elements = document.getElementsByClassName("copycode");
for (var i = 0; i < elements.length; i++) {
elements[i].setAttribute("target", "foo");
}
You can't have more than one ID with the same name, ID should be unique per page.
The getElementById() method accesses the first element with the specified id.
If you want get all the input element then you should try getElementsByTagName()
The getElementsByTagName() method accesses all elements with the specified tagname.
document.getElementsByTagName("input");
var elements = document.getElementsByTagName("input");
alert(elements);
for(var i = 0; i < elements.length; i++)
{
//add the target to the element
}
Hope this helps!
<body>
<span someAttribute="xyz">.....</span>
...
<div>
...
<span someAttribute="abc">.....</span>
...
<div someAttribute="pqr">.....</div>
...
</div>
</body>
Here is a sample html page.. I need to select the html elements by its attributes i can get the attribute values by getAttribute() but i need to select all the elements first.
How in javascript to get elements which has the attribute name as "someAttribute". Once i get the elements i can get the attribute values and use my function.
Note: i want to do this without using jquery.
In new browsers you can do:
var el = document.querySelector('[someAttribute="someValue"]');
store each element in a array the loop throught each element, and if the element contains the attribute someAttribute do somgthing.
var arr_elms = [];
arr_elms = document.body.getElementsByTagName("*");
var elms_len = arr_elms.length;
for (var i = 0; i < elms_len; i++) {
if(arr_elms[i].getAttribute("someAttribute") != null){
alert("FOUND : " + arr_elms[i].getAttribute("someAttribute"));
}
}
You can select elements by tag name using document.body.getElementsByTagName("div") to get all the div elements inside your document. This function returns an array of elements, which you can parse and filter out elements that don't match your criteria.
You can traver all elements of DOM tree.
you can use
var all = document.getElementsByTagName('*');
but this also returns the html, head and body ...
and then do a loop over all elements and look for the attributes.
I found a snippet called getElementsByAttribute(doc, tagArray, attribute, attributeValue)
You can give a try to a working fiddle: http://jsfiddle.net/Yx7EU/
Hope this can help.
For instance in the snippet below - how do I access the h1 element knowing the ID of parent element (header-inner div)?
<div id='header-inner'>
<div class='titlewrapper'>
<h1 class='title'>
Some text I want to change
</h1>
</div>
</div>
Thanks!
function findFirstDescendant(parent, tagname)
{
parent = document.getElementById(parent);
var descendants = parent.getElementsByTagName(tagname);
if ( descendants.length )
return descendants[0];
return null;
}
var header = findFirstDescendant("header-inner", "h1");
Finds the element with the given ID, queries for descendants with a given tag name, returns the first one. You could also loop on descendants to filter by other criteria; if you start heading in that direction, i recommend you check out a pre-built library such as jQuery (will save you a good deal of time writing this stuff, it gets somewhat tricky).
If you were to use jQuery as mentioned by some posters, you can get access to the element very easily like so (though technically this would return a collection of matching elements if there were more than one H1 descendant):
var element = $('#header-inner h1');
Using a library like JQuery makes things like this trivial compared to the normal ways as mentioned in other posts. Then once you have a reference to it in a jQuery object, you have even more functions available to easily manipulate its content and appearance.
If you are sure that there is only one H1 element in your div:
var parent = document.getElementById('header-inner');
var element = parent.GetElementsByTagName('h1')[0];
Going through descendants,as Shog9 showed, is a good way too.
It's been a few years since this question was asked and answered. In modern DOM, you could use querySelector:
document.querySelector('#header-inner h1').textContent = 'Different text';
<div id='header-inner'>
<div class='titlewrapper'>
<h1 class='title'>
Some text I want to change
</h1>
</div>
</div>
The simplest way of doing it with your current markup is:
document.getElementById('header-inner').getElementsByTagName('h1')[0].innerHTML = 'new text';
This assumes your H1 tag is always the first one within the 'header-inner' element.
To get the children nodes, use obj.childNodes, that returns a collection object.
To get the first child, use list[0], that returns a node.
So the complete code should be:
var div = document.getElementById('header-inner');
var divTitleWrapper = div.childNodes[0];
var h1 = divTitleWrapper.childNodes[0];
If you want to iterate over all the children, comparing if they are of class “title”, you can iterate using a for loop and the className attribute.
The code should be:
var h1 = null;
var nodeList = divTitleWrapper.childNodes;
for (i =0;i < nodeList.length;i++){
var node = nodeList[i];
if(node.className == 'title' && node.tagName == 'H1'){
h1 = node;
}
}
Here I get the H1 elements value in a div where the H1 element which has CSS class="myheader":
var nodes = document.getElementById("mydiv")
.getElementsByTagName("H1");
for(i=0;i<nodes.length;i++)
{
if(nodes.item(i).getAttribute("class") == "myheader")
alert(nodes.item(i).innerHTML);
}
Here is the markup:
<div id="mydiv">
<h1 class="myheader">Hello</h1>
</div>
I would also recommend to use jQuery if you need a heavy parsing for your DOM.