jQuery get attributes and values of element - javascript

Say I have this HTML code:
<img id="idgoeshere" src="srcgoeshere" otherproperty="value" />
I can reference the element by its id: $('#idgoeshere')) Now, I want to get all the properties and their values on that element:
src=srcgoeshere
otherproperty=value
Is there some way I can do that programmatically using jQuery and/or plain Javascript?

You can get a listing by inspecting the attributes property:
var attributes = document.getElementById('idgoeshere').attributes;
// OR
var attributes = $('#idgoeshere')[0].attributes;
alert(attributes[0].name);
alert(attributes[0].value);
$(attributes).each(function()
{
// Loop over each attribute
});

The syntax is
$('idgoeshere').attr('otherproperty')
For more information - http://api.jquery.com/attr/

Yes you can!
Jquery:
var src = $('#idgoeshere').attr('src');
var otherproperty = $('#idgoeshere').attr('otherproperty');
Javascript:
var src = document.getElementById('idgoeshere').getAttribute('src');
var otherproperty = document.getElementById('idgoeshere').getAttribute('otherproperty');

You can use attr for that:
For eg.
var mySrc = $('#idgoeshere').attr("src");
var otherProp = $('#idgoeshere').attr("otherproperty");

If you want to just get a list of all the attributes, see the answers to this question: Get all Attributes from a HTML element with Javascript/jQuery

Try this:
var element = $("#idgoeshere");
$(element[0].attributes).each(function() {
console.log(this.nodeName+':'+this.nodeValue);});

Related

How to clone an element using class name and append it to the body

I am trying to learn how to clone an element using classname and append it to the body.
here is what i have done but i am not getting any output. is there anything wrong ?
HTML:
<div class="check">hello</div>
CSS:
.check {
top: 100px;
}
JavaScript:
var elem = document.getElementsByClassName('.check');
var temp = elem[0].clonenode(true);
document.body.append(temp);
JSFiddle Link:
http://jsfiddle.net/hAw53/378/
if not JS, jquery solution is also welcomed.
You were almost there:
var elem = document.getElementsByClassName('check'); // remove the dot from the class name
var temp = elem[0].cloneNode(true); // capitalise "Node"
document.body.appendChild(temp); // change "append" to "appendChild"
<div class="check">hello</div>
You have 3 errors. Correct code:
var elem = document.getElementsByClassName('check'); // check, not .check
var temp = elem[0].cloneNode(true); // cloneNode, not clonenode
document.body.appendChild(temp); // appendChild, not append
Demo: http://jsfiddle.net/hAw53/379/
There are a few issues with your code.
getElementsByClassName() takes a class name (check), not a selector (.check)
cloneNode() is spelled with a capital N (not clonenode())
appendChild() is the name of the DOM method for appending a child (not append())
Correct version:
var elem = document.getElementsByClassName('check');
var temp = elem[0].cloneNode(true);
document.body.appendChild(temp);
You can do:
$('.check').clone().appendTo('body');
You're code had errors. First you used class selector and not the class name. Then you used an undefined property(properties are case sensitive) and you've to use appendChild instead of append which is a part of jQuery. You're too much confused with native javascript and jQuery.
in Jquery it's very simple, you just need to define inside what the new element apears.
var elem = $('.check');
elem.clone().prependTo( "body");

How to create a DOM element from a template?

Suppose I have a template saved in HTML and using standard underscore syntax.
My understanding is that I can grab the template using jQuery as such:
var html = $('#item-foo').html()
From there I can interpolate it using
var interpolated = _.template(html, {prop: "and_values"});
To create a DOM element in the JavaScript I can use this utility function
// converts HTML string to DOM object
Pub.HTMLToElement = function (html) {
var div = document.createElement('div');
div.innerHTML = html;
return div.firstChild;
};
var element = HTMLToElement(interpolated);
and finally I have my element in JavaScript which all began with a template in the HTML.
Is this the best way to do this?
It seemed long so I just wanted to validate.
This is a little bit simpler and you are already using jQuery:
HTML:
<script id="template" type="text/template">
Hello <%=name%>, how are you?
</script>
<div id="container" />
JS:
var str=$('#template').html();
var interpolated = _.template(str, {name: "pizza"});
$('#container').append($('<div/>').html(interpolated));
JSFiddle: http://jsfiddle.net/QAT4n/
If you are using jQuery, jQuery automatically converts HTML to an element. This would be a shorter way:
var element = $(interpolated).get(0);
See http://api.jquery.com/get/ and http://api.jquery.com/jQuery/#jQuery2
So the whole process would be like this:
var html = $('#item-foo').html()
var interpolated = _.template(html, {prop: "and_values"});
var element = $(interpolated).get(0);
And could be cleaned up to this:
var interpolated = _.template(
$('#item-foo').html()
, {
prop: "and_values"
});
var element = $(interpolated).get(0);

jquery after method not returning generated element

In the following code:
var genContent = "<tr><td>please wait!!!</td></tr>";
var outputElement = $("#projectsTable tr:first").after(genContent);
myForm = $(this).find("form");
submitForm(myForm, outputElement);
I expect outputElement to be the element generated by the after method from jquery, but for some reason outputElement is refering to the table headers.
What do I need to do to get the newly generated element?
You need to use .insertAfter() if you want outputElement to refer to the tr element
var = "<tr><td>please wait!!!</td></tr>";
var outputElement = $(genContent).insertAfter("#projectsTable tr:first");
myForm = $(this).find("form");
submitForm(myForm, outputElement);
The after method inserts element(s) after the current selection, and returns that same current selection. So it does not change the selection. If you need the elements that you want to insert, maybe create a jQuery object of it, and insert that.
var genContent = "<tr><td>please wait!!!</td></tr>";
var outputElement = $(genContent);
$("#projectsTable tr:first").after(outputElement);

Parse a string in jquery, change something and get the modified string back

I have a string containing html code, something like this: http://jsbin.com/ocoteg/1.
I want to parse this string, make some changes (just for example: change all links to a span), and then get the modified html string back.
Here is a jsbin, where I started this, but I can't make it work: http://jsbin.com/okireb/1/edit.
I get the html string, I parse it with jquery, but I can't replace the links, and get the modified html string back.
UPDATE
Why the downvote? What is the problem with this question?
You can do it in a loop also
dom.each(function(i,v){
if(v.tagName == "A"){
dom[i] = $('<span/>').html($(v).html())[0]; // replace it right away with new span element
}
});
var newString = $('<div>').append(dom.clone()).html(); //<-- to get new string http://stackoverflow.com/a/652771/1385672
console.log(newString);​
EDIT:
Here's how you can do it keeping the other tags
var dom = $(text.split('\n'));
$(dom).each(function(i,v){
var ele = $(v)[0];
if($(ele).is('a')){
dom[i] = $('<div>').append($('<span/>').html($(v).html())).html();
}
});
var newString = dom.get().join('\n');
http://jsbin.com/okireb/32/edit
Use find instead of filter :
var dom = $('<div>'+text+'</div>');
dom.find('a').each(function() {
var el = $(this);
var html = el.html();
var span = $('<span/>').html(html);
el.replaceWith(span);
});
console.log(dom.children()); ​
Note that I wrap everything for the case where the initial dom isn't one element.
Demonstration
To get the html back as a string use
var html = dom.html();
This should be what you want (can be improved)
var text = '<!DOCTYPE html><html><head><meta charset=utf-8 /><title>JS Bin</title></head><body>Link 1Link 2Link 3</body></html>';
var body_content = text.substring(text.indexOf('<body>') + 6, text.indexOf('</body>'));
var $dom = $('<div/>').html(body_content);
$('a', $dom).each(function() {
$('<span>' + $(this).html() + '</span>').insertAfter($(this));
$(this).remove();
});
var text_new = text.replace(body_content, $dom.html());
// text_new contains the entire HTML document with the links changed into spans
You could do it with .replace.
Probably not the nicest way of doing it though.
dom = dom.replace(/<a /g,'<span');
dom = dom.replace(/<\/a>/g,'</span>');
Demo: http://jsbin.com/okireb/14/edit

Access a label's attribute using jquery

I have some data coming from the server in which I fill A Div in the Html page with.
The way I write the div is as follows:
<div class="BigDiv"><label class = "AttList" Std_Id="' + Std_Id + '">' + Std_Name +'</label></div>
Now, I want the data inside this div.
There are some other labels inside the div so I use this.children to access this label.
var labels = $(this).children('div');
var StdName = this.children[0].childNodes[0].nodeValue;
I want to access the Std_Id inside the Std_Id attribute, but I don't know how to do it ... Do you have any ideas?
Thanks.
Assuming that $(this) is a reference to the .BigDiv element:
var StdName = $(this).find('label').attr('Std_Id');
Or, similarly, and with the assumption that this is the .BigDiv element:
var children = this.childNodes;
for (var i=0,len=children.length; i<len; i++){
if (children[i].nodeType == 1 && children[i].tagName.toLowerCase() == 'label'){
var StdName = this.getAttribute('Std_Id');
}
}
References:
jQuery:
attr().
find().
JavaScript
element.getAttribute().
node.nodeType.
tagName.
toLowerCase().
Use getAttribute:
var labels = $(this).children('div');
var StdId = this.children[0].getAttribute("Std_Id");
Note that, according to the HTML5 spec, custom attributes should start with data-, though most browsers can tolerate it.
To save elements, which were selected using a jQuery-Selector, do this:
$labels = $('.BigDiv').find('label');
Now you can loop through each label with jQuery's foreach loop:
$.each($labels, function() {
var std_id = $(this).attr('Std_Id');
// do something with std_id
});
You could use the attr method as such,
var value = $('.AttList').attr('Std_Id');
EDIT
OK, so you for your implementation, you need to do this...
var value = $(this).find('.AttList').attr('Std_Id');
Assuming that this is the div or the parent of that div

Categories