i'm having a bug on firefox 3.6 using this function
function GetRefreshedResults(response)
{
var splitted = response.value.split("|");
var panel = document.getElementById('my-glider');
var anchors = panel.getElementsByTagName('a');
for (var i=0; i<anchors.length; i++)
{
anchors[i].innerHTML=splitted[i];
}
}
which ads in DOM anchors like
"< a xmlns="http://www.w3.org/1999/xhtml">
I'm now trying to use this instead:
function GetRefreshedResults(response)
{
var splitted = response.value.split("|");
var panel = document.getElementById('my-glider');
var anchors = panel.getElementsByTagName('a');
for (var i=0; i<anchors.length; i++)
{
anchors[i].empty();
anchors[i].appendChild(splitted[i]);
// anchors[i].innerHTML=splitted[i];
}
}
but i get the following error in appendChild :
Uncaught Error: NOT_FOUND_ERR: DOM Exception 8
i don't understand why it's not working. can anyone help me ?
thanks
EDIT:
Example:
splitted[0] contains :
"<div class="var">Visits</div><div class="percent-zero">0%</div><div class="val">0<div class="val-alt">Unique Visits: 0</div></div>"
i want to update 8 anchors with new content, contained in splitted[0], splitted[1]...splitted[7]
splitted[i] is the problem. appendChild appends a DOM-element to an existing DOM-element, but it looks like you ar trying to append a string value. If you want to use appendChild, either create a container element and use innerHTML for that to insert the string, or just use innerHTML. It is not a bug that you can't append a string as DOM-element, I'd say. See also the MDN-page on appendChild.
response.value.split("|"); Indicates to me that you are passing response as a string. appendChild only works with elements. You can't append a child to a flat string.
Related
I want to take the second class of an element, and then add a class to the element that has that ID. In Chrome, Firefox, etc. it works perfectly but in IE11 it does not. Do you know why? Help me please
for (var i = 0; i < $('#example .item').length; i++) {
var class_svg = document.getElementsByClassName("item")[i].className.split(' ')[1];
var $elem = document.getElementById(class_svg);
$elem.classList.add("show");
}
According to the docs classList is only partially supported before Edge. Use className instead like:
$elem.className += ' show';
edit: thanks for the hint #Sterling Archer
Creating a basic example using an SVG element (which I assume you have based on your example code) and looking at it in IE11 and Edge, you can see that the className property is a [object SVGAnimatedString]. That is some special object for SVG elements, instead of dealing with that special object, lets just deal with the attribute itself using getAttribute. Here is the code that works in most all browsers:
for (var i = 0; i < $('#example .item').length; i++) {
var class_svg = document.getElementsByClassName("item")[i].getAttribute("class").split(' ')[1];
var $elem = document.getElementById(class_svg);
var classList = $elem.getAttribute("class");
classList += " show";
$elem.setAttribute("class",classList);
}
Hope that works for you.
I've got a bit of jQuery that outputs some HTML to an id, however in my code it must output to a class. Any ideas how I can achieve this?
document.getElementById("content").innerHTML=output;
<div class="content> </div>
I've tried getElementsByClass but it doesn't seem to work for me.
What you have there isn't jquery, it's raw JS and if you already have jQuery in your project, it's a bit easier with jQuery:
$(".content").html(output);
Use the getElementsByClassName method.
[0] is missed in the javascript. Thats the reason , you are not able fetch the records.
document.getElementsByClassName("content")[0].innerHTML = output;
getElementsByClassName returns an array of all matching elements. Try looping through this array and adjusting each array item
var elements = document.getElementsByClassName('class-name');
for ( var i = 0; i < elements.length; i++ )
{
elements[i].innerHTML = output;
}
getElementsByClassName returns an array, so assuming this is the first content in your document, use:
document.getElementsByClassName("content")[0].innerHTML = output;
If there are more than one element, you'd use a loop to loop through them and target the element you wish, e.g
var content = document.getElementsByClassName('content');
for (var i = 0; i < content.length; i++) {
content[1].innerHTML = "Second element with class content";
content[3].innerHTML = "Fourth element with class content";
}
jsFiddle here
You can use querySelectorAll for this purpose
document.querySelectorAll(".content")[0].innerHTML = output;
documet.querySelectorAll returns the elements with matching selectors.
I would like to get all the elements/nodes in an HTML page which contain attributes that start with something (again, the attribute names start with something, not their values!). For example, TinyMCE has a tendency of adding custom attributes to the elements it saves, like "mce_style", "mce_href", "mce_bogus", etc. I would like to have something like the CSS3 selector for attribute values, [attr^="mce_"], but not for the values, the attribute names.
Of course, I can iterate through all DOM nodes and their attributes and check them one by one, but I was wondering whether there is a more efficient way.
Please don't give me TinyMCE-specific answers, I'm pretty sure there's a flag which would prevent TinyMCE for saving these attributes, but the question is generic.
here's a simple demo to find all elements that contain an attribute starting with mce_. might need some refinements.
function getMCE() {
var el, attr, i, j, arr = [],
reg = new RegExp('^mce_', 'i'), //case insensitive mce_ pattern
els = document.body.getElementsByTagName('*'); //get all tags in body
for (i = 0; i < els.length; i++) { //loop through all tags
el = els[i] //our current element
attr = el.attributes; //its attributes
dance: for (j = 0; j < attr.length; j++) { //loop through all attributes
if (reg.test(attr[j].name)) { //if an attribute starts with mce_
arr.push(el); //push to collection
break dance; //break this loop
}
}
}
return arr;
}
console.log(getMCE())
Try this:
FUNCTIONS
//custom selector expression
$.extend($.expr[':'],{
attr:function(o,i,m){
var attrs=$.getAttrAll(o),re=m[3],found=false;
$.each(attrs,function(k,v){
if(new RegExp(re).test(v)) { return found=true;}
});
return found;
}
});
// get all atrributes of an element
$.getAttrAll=function(el){
var rect = [];
for (var i=0, attrs=el.attributes, len=attrs.length; i<len; i++){
rect.push(attrs.item(i).nodeName);
}
return rect;
};
`
USAGE
// calling custom selector expression :attr(regexp)
$(function(){
$('body').find(':attr("^mce_")').css({background:'yellow'});
});
HTML
<body>
<p mce_style="height:50px" id="x" data-hello="hello">selected</p>
<div not_mce_bogus="abc">not_mce_bogus</div>
<div mce_href="http://rahenrangan.com">selected</div>
<p>othrs</p>
</body>
One option, if you don't mind temporarily altering your DOM, is to extract your HTML into a string and search for the attributes via RegExp. When you find the attributes, you could append a "needle" in the DOM so that you can use jQuery to select the elements.
Here is a working concept (run with console open):
http://jsfiddle.net/skylar/N43Bm/
Code:
$.fn.extend({
findAttributes: function(attribute) {
var attributeFinder = new RegExp(attribute + '(.+)="', "gi");
var elementHTML = this.html().replace(attributeFinder, "data-needle='pin' "+attribute+"$1=\"");
this.html(elementHTML);
return this.find("[data-needle=pin]").removeAttr('data-needle');
}
});
console.log($("body").findAttributes('mce_'));
Note: my regexp is not great. You'll have to take better care than I have in this example.
Try this: (I tried putting * instead of a tag but it colored all the elements including those who do not have mce_style attribute as well)
a[mce_style] { color : red; }
Demo : http://jsfiddle.net/Tcdmb/
More info : https://developer.mozilla.org/en/CSS/Attribute_selectors
I have an element with multiple elements inside. All of the elements inside have the same name. Is there any way to remove them using one function?
(refer to this question for example Remove multiple children from parent?
Here's a solution that removes the first level children with the specified name for the parent with the specified id. If you want to go deeper, you can recursively call it on the child elements you get inside (you'll have to add a parent parameter as well).
function removeChildren (params){
var parentId = params.parentId;
var childName = params.childName;
var childNodes = document.getElementById(parentId).childNodes;
for(var i=childNodes.length-1;i >= 0;i--){
var childNode = childNodes[i];
if(childNode.name == 'foo'){
childNode.parentNode.removeChild(childNode);
}
}
}
And to call it:
removeChildren({parentId:'div1',childName:'foo'});
And a fiddle for testing:
Notes: You can only access the name element dependably in JavaScript when it supported on your element (e.g. NOT on DIVs!). See here for why.
UPDATE:
Here's a solution using className based on our conversation:
function removeChildren (params){
var parentId = params.parentId;
var childName = params.childName;
var childNodesToRemove = document.getElementById(parentId).getElementsByClassName('foo');
for(var i=childNodesToRemove.length-1;i >= 0;i--){
var childNode = childNodesToRemove[i];
childNode.parentNode.removeChild(childNode);
}
}
2021 Answer:
Perhaps there are lots of way to do it, such as Element.replaceChildren().
I would like to show you an effective solution with only one redraw & reflow supporting all ES6+ browsers.
function removeChildren(cssSelector, parentNode){
var elements = parentNode.querySelectorAll(cssSelector);
let fragment = document.createDocumentFragment();
fragment.textContent=' ';
fragment.firstChild.replaceWith(...elements);
}
Usage: removeChildren('.foo',document.body);: remove all elements with className foo in <body>
ok this should be easy. First get the parent element:
var theParent = document.getElementById("notSoHappyFather");
then get an array of the nodes that you want to remove:
var theChildren = theParent.getElementsByName("unluckyChild");
Lastly, remove them with a loop:
for (var i = 0; i < theChildren.length; i++)
{
theParent.removeChild(theChildren[i]);
}
A sample of your HTML would get you a more complete answer, but one can fairly easy call DOM functions to get the list of children and just remove them. In jQuery, remove all children would be something like this:
$("#target > *").remove();
or
$("#target").html("");
And, you can see a demo here: http://jsfiddle.net/jfriend00/ZBYCh/
Or, not using jQuery you could also do:
document.getElementById("target").innerHTML = "";
If you're trying to only remove a subset of the children (and leave others intact), then you need to be more specific how one would determine which children to leave and which to remove. In jQuery, you could use a .find() select or a filter() selector to narrow the list of children to just the children you wanted to target for removal.
I am currently have a chunk of string which actually a html source code stored in it. What I am trying to do now is to read out specific tags which I require using javascript. Can anyone help me with this, I am new to programming and I am not too sure how to go about it.
The problematic code:
if (request.readyState == 4) {
var html_text = request.responseText;
var parent = document.createElement('div');
parent.innerHTML = html_code;
var metas = parent.getElementsByTagName('meta');
var meta;
for (var i = 0; i < metas.length; i++) {
meta = metas[i];
alert(meta.property);
alert(meta.content);
}
}
The meta content works, but just that the meta property returned are undefined.
Use the DOM (Document Object Model) API. The Mozilla Dev Network (née Mozilla Dev Center) is a great starting point an all-around reference.
JavaScript Guide
The DOM and JavaScript
Traversing an HTML table with JavaScript and DOM Interfaces
What I am trying to do now is to read out specific tags which I require using javascript.
var text = /* whatever string that contains HTML */;
First you need to parse the string:
var parent = document.createElement('div');
parent.innerHTML = text;
Then you can search for whatever kind of element you're looking for. Say you're looking for <table> elements.
var tables = parent.getElementsByTagName('table');
Now you can do whatever you need to each element found:
var table;
for (var i=0, len=tables.length; i<len; i++)
{
table = tables[i];
// do something with the element
}
Relevant API docs
document.createElement
element.innerHTML
element.getElementsByTagName
Attributes of XML nodes are not readily available as DOM object properties. Use getAttribute
Sample: http://jsfiddle.net/mendesjuan/6Pdmw/
var node = document.createElement('div');
node.innerHTML = "<meta property='prop1' content='cont1'>"+
"<meta property='prop2' content='cont2'>";
var metas = node.getElementsByTagName('meta');
for (var i = 0; i < metas.length; i++) {
var meta = metas[i];
alert(meta.getAttribute("property"));
alert(meta.getAttribute("content"));
}