Remove characters from an element while using appendChild - javascript

I'm trying to remove or replace characters in an element while using appendChild as follow:
var options = from.getElementsByTagName("option");
var to = document.getElementById("target");
to.appendChild(options[i].replace("(A)",""));
I tried various different syntax but no luck. Can someone help? Either JQuery or javascript works for me.
Thanks

I assume you're already in a for loop. If so, use the .text property of the option element, and create a new text node.
to.appendChild(document.createTextNode(options[i].text.replace("(A)","")));
Or better, in the loop append to a string, and create a single node at the end.
var txt = "":
for (var i = 0; i < options.length; ++i)
txt += options[i].text.replace("(A)"), "");
}
to.appendChild(document.createTextNode(txt));
If you actually wanted to append a copy of the element itself, then use .cloneNode(true) instead.
for (var i = 0; i < options.length; ++i) {
var clone = to.appendChild(options[i].cloneNode(true));
clone.text = clone.text.replace("(A)", "");
}

Related

Give params to a div created via document.createElement

I want to create multiple divs using a for loop which i do it like this
for(let i = 0; i < data.length; i++) {
let divs = document.createElement('div');
divs.className = 'button';
divs.data-id = (data[i]).id; // error
document.body.appendChild(divs);
}
Now my issue is that data-id is required but it pops an error. So how can I define data-id dynamically
I also tried giving the whole div as innerHTML of another div but then it wont render. So how can this be solved??
Use setAttribute() instead:
divs.setAttribute('data-id' , data[i].id);
Also note that hyphens are not allowed in Javascript identifiers, they would be parsed as substraction.
You're looking for divs.setAttribute('data-id', data[i].id);.
If you were trying to read an attribute with a funky character such as that dash in your example, you would access it with brackets instead of dot notation and quote the attribute like so: divs.attributes['data-id']
This should work:
for(let i = 0; i < data.length; i++) {
let divs = document.createElement('div');
divs.setAttribute("id", "btn_id");
divs.setAttribute("class", "btn_class");
divs.setAttribute("data-id", (data[i]).id);
document.body.appendChild(divs);
}
Or use Jquery alternatives:
var newDiv= $('<div/>', { id: 'foo', class: 'tclose'})
for(let i = 0; i < data.length; i++) {
let divs = document.createElement('div');
var attr = document.createAttribute('data-id');
attr.value = (data[i]).id;
divs.setAttributeNode(attr);
document.body.appendChild(divs);
}

How to get the result of the clone() function from javascript?

this is my code :
html = "";
for (i = 0; i < id_array.length; i++){
html = html.concat($(id_array[i]).clone(true));
}
console.log(html);
The id_array contains 3 ids of the <tr> tag . Instead of the html code from the ids , the result of the html variable is object object object ... Why ? How do I get the html code from this id ?
This is my html code , it is not written by me , it is generated by JQgrid plugin. so i took a picture:
It looks like your want to call outerHTML. In order to do it, you need the native DOM element, you can get it using [0] or get(0) :
var html = "";
for (i = 0; i < id_array.length; i++){
html += $(id_array[i])[0].outerHTML;
}
console.log(html);
clone returns jQuery objects. You don't want to concat them with an empty string. Instead, use an array to store them:
trs = [];
for (i = 0; i < id_array.length; i++){
trs.push($(id_array[i]).clone(true));
}
console.log(trs);
You don't want to use HTML strings when dealing with the DOM.
It seems you may want the outer HTML of the TR elements. Some browsers support it, but not all (and surprisingly not jQuery). In this case you can do something like:
var id_array = ['tr0','tr1','tr2'];
var html = "";
var tbody = $('<tbody>');
for (i = 0; i < id_array.length; i++) {
tbody.append($('#' + id_array[i]).clone(true));
html += tbody.html();
tbody.html('');
}

get the text of a div

I have been trying to get the text from a div using only javascript.
I started with jQuery using the following code:
var divText = $("div.Xr3").html();
Then for my JavaScript I tried:
var divText = document.getElementsByClassName("Xr3").innerHtml;
Which returns undefined. How can I accomplish this using JavaScript only?
getElementsByClassName returns a live array of HTML elements, so you can't access innerHTML directly like this. You will either have to loop over its results, or if you know there's only one, apply [0] to it before accessing innerHTML.
var divTexts = [];
var divs = document.getElementsByClassName("Xr3");
var numDivs = divs.length;
while (var i = 0; i < numDivs; i++) {
divTexts.push(divs[i].innerHtml);
}
or, in a single-element scenario,
var divText = document.getElementsByClassName("Xr3")[0].innerHtml;
If Xr3 is used one time, you can use
var divText = document.getElementsByClassName("Xr3")[0].innerHtml;

Combining jQuery with native JS in DOM creation

I'm reusing an old application of mine and want to change the code so I'm applying the DOM structure that I build up to a node's class instead of it's id.
Below is a piece of the code and as you can see I try to combine jQuery (getting the node by it's class) with the old structure, but something doesn't work properly here.
Is it possible to combine jQuery and JS native like this?
If not, is there another way to accomplish what I want to do?
var gamearea = $('<div/>', {
text': 'testarea',
class': 'gamearea'
}).appendTo('.memory:last');
alert("this.rows: " + this.rows);
for (var j = 0; j < this.rows; j++){
var box = document.createElement('div');
for (var i = 0; i < this.cols; i++){
var iterator = (this.cols * j) + i;
var img = document.createElement('img');
var aNod = document.createElement('a');
aNod.href = "#";
img.src = "pics/0.png";
aNod.appendChild(img);
box.appendChild(aNod);
}
gamearea.appendChild(box);
}
You should be able to get it working by changing gamearea.appendChild(box); to gamearea[0].appendChild(box);
The reason behind that is you can get the bare DOM element for a jQuery extended object by simply doing obj[0], where obj is a jQuery extended object obtained like obj = $(...) etc. And the appendChild method in your code is a method of bare DOM element.

Optimization appending <li> into <ul> with jQuery

I populate a list with search results appending li elements. I update DOM for each result.
for (var i = 0; i < topics.length; i++) {
$("#searchResults").append(
$("<li />")
.append(result.Name)
.addClass("example")
);
};
I want to make a group of li elements first and update DOM-tree just once.
I try something like this:
var list = $([]);
for (var i = 0; i < topics.length; i++) {
list.append(
$("<li />")
.append(result.Name)
.addClass("example")
);
};
$("#searchResults").append(list);
But div $("#searchResults") is empty.
Where is the problem?
Something like this should be much faster:
var ul = $("<ul />");
for (var i = 0, l=topics.length; i < l; i++) {
$("<li />", { text: result.Name, "class": "example" }).appendTo(ul);
};
$("#searchResults").append(ul.contents());
By using a document fragment ($("<ul />")) and appending to it, then appending at the end, we're not messing with the entire DOM each append. Also we're not repeatedly selecting #searchResults each loop...or checking .length would could also be expensive.
Note: this method still uses the DOM to create elements (as opposed to a string), eliminating issues of result.Name having HTML that could screw things up, etc.
Creating DOM elements on the fly will usually be slower than just using innerHTML (or a wrapper around that). Also, concatenating string with + will usually be slower than using Array.join('').
In the end, I suspect something like this would be the fastest:
var list = [];
for (var i = 0; i < topics.length; i++)
list.push("<li class=example>",topics[i].Name,"</li>");
$("#searchResults").html(list.join(''));
Try just using a string. Add all your li's to a string and then put them into the innerHTML of the searchResults div.
var list = '';
for (var i = 0; i < topics.length; i++) {
list +="<li class=example>" + result.Name + "</li>";
}
$("#searchResults").innerHTML = list;
If you are looking for efficacy this is probably better because you are not using the DOM engines a lot. (although unless you are adding hundreds of li's it is probably insignificant anyway.
All previous solutions still suffer from recalculating, painting and layout for every single element we add.
Instead of appending the elements directly to the document when they are created, append them to the DocumentFragment instead, and finish by adding that to the DOM.
var el;
var i = 0;
var fragment = document.createDocumentFragment();
while (i < 500) {
el = document.createElement('li');
el.innerText = '1ist ' + i;
fragment.appendChild(el);
i++;
}
div.appendChild(fragment);

Categories