Change an element itself with jquery or Raw javascript - javascript

is there any way we can change an element itself with jQuery or basic Javascript. for example : we have an Html Tag as <a href="mysite.com" title='titlevalue'>Link</a>, can we replace it like this <a href="mysite.com" data-title='titlevalue'>Link</a>.
Yeah, we can do add/remove title/data-title attribute however we have quite a lot of links so it would be better if we can have such sort of things. Searched on Google and here but didn't find anything like this, just changing the values of an attribute and add/remove of attributes.
Please Advice.
Thanks

If you want to add the data title attribute to each anchor tag, by using the value in the title attribute, you can do something like this:
$("a").each(function(){
$(this).attr("data-title", $(this).attr("title"));
$(this).removeAttr("title");
});

That will change title to data-title in all a-Tags:
$("a").each(function() {
$(this).attr("data-title", $(this).attr("title"));
$(this).data("title", $(this).attr("title"));
$(this).removeAttr("title");
});
http://jsfiddle.net/eC2cQ/

Hmm... without jQuery... (just because it's always nice to have that option)
var el = document.getElementsByTagName("a");
for(i=0; i < el.length; i++) {
el[i].setAttribute("data-title", el[i].getAttribute("title"));
el[i].removeAttribute("title");
}

Could be done like that too:
$('a').attr('data-title', function () {
return this.title
}).removeAttr('title');

Using jQuery, you could do the following:
// find each a tag with a title attribute
$( 'a[title]' ).each( function ( index, item ) {
// cache your jQuery object
var $item = $(item);
// replace and remove the attributes
$item.attr( 'data-title', $item.attr( 'title' ) );
$item.removeAttr( 'title' );
});
Some points of note:
if you want custom attributes on elements in new pages, you are
better off changing your back-end process to create these new
attributes. To expand on this: if you are hand-coding new pages,
simply write out the new attributes; if you are using a server-side
technology, use the templating system you're already using to write
out these new attributes.
your example is not good practice: title attributes are useful to
many people and machines. Replacing them with data-title prevents
a lot of standard tech from finding the information contained in them. There is extra
meaning implied by data-attributes, that they are extra,
application-specific information, and link titles are better used in
the generic way.
it's redundant: if you can read a
data-attribute, you can also read a normal attribute.
there will be other ways to do this without using jQuery, but it's a pretty typical library in use these days

Related

Is it okay to use attributes from a tag in another tag?

I would like to know if it is a problem to use an attribute of a tag in another tag, which does not have this attribute.
For example: in the <video> attribute we have src.
If I put <p src="..."> will there be any problem? I know it's wrong, but it's just a question!
I ask this because I can capture the src attribute inside P using javascript. Example:
var tag = document.getElementsByTagName("p")
for (var i = 0; i < tag.length; i++) {
alert(tag.item(i).getAttribute("src"))
}
<p src="...">Hello!</p>
I would like to know if there is any limitation for this, or if there will be any incompatibility.
Thanks.
You can use an attribute with data- preffix for that purpose.
Custom data attributes are intended to store custom data, state, annotations, and similar, private to the page or application, for which there are no more appropriate attributes or elements.
source: https://html.spec.whatwg.org/#custom-data-attribute
So, in your case it could be something like that:
var tag = document.getElementsByTagName("p")
for (var i = 0; i < tag.length; i++) {
alert(tag.item(i).getAttribute("data-src"))
}
<p data-src="...">Hello!</p>
If you don't do that, you may face compatibility issues in the future.
No limits. In fact in HTML5 spec you can define your own custom nodes.
Indeed adding additional attributes to exiting element (such as a p) will yield best-practice warnings.
https://www.w3.org/TR/2011/WD-html5-20110525/elements.html#elements-in-the-dom
However there is a convenient place for custom attributes within the data-* attributes:
<p data-src='//custom/path.png'></p>
Then you have the added bonus of the js dataset:
let $node = $('p')
$node.dataset.src == '//custom/path.png'
https://www.w3.org/TR/2011/WD-html5-20110525/elements.html#embedding-custom-non-visible-data-with-the-data-attributes
But also you can also invent your own nodes:
<mycustomnode></mycustomnode>
Aside from that - go nuts!
Better avoid using attributes that are not part of the tag. Use the data attributes for that:
const tag = document.querySelector('p');
console.log({
foo: tag.dataset.foo,
moo: tag.dataset.moo
});
<p data-foo="bar" data-moo="goo">Hello dataset</b>
Docs: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

How to add id's and values to a article tag dynamically through jquery?

I need to add a mix of ids and path to the article element dynamically through jquery
This is the HTML article tag
<article class=test> <article/>
I tried to do this in jquery.
var assetHtml='data-asset-share-id="asset" data-asset-share-asset="/dam/pic.jpg" id="/dam/pic.jpg"';
$( ".test" ).append(assetHtml);
But this adds the entire id and elements in a string format something like this in quotes making it a string whereas they are id's in the text area of article tag instead of inside article tag
<article class="test">"data-asset-share-id="asset" data-asset-share-asset="/dam/pic.jpg" id="/dam/pic.jpg""</article>
I expect the output to be in this format
<article class=test data-asset-share-id="asset" data-asset-share-asset="/dam/pic.jpg" id="/dam/pic.jpg" > </article>
How to achieve this?
append() is used to add content within an element. To amend the attributes of the element to it you can use attr():
$(".test").attr({
'data-asset-share-id': 'asset',
'data-asset-share-asset': '/dam/pic.jpg',
'id': '/dam/pic.jpg'
});
Alternatively you can use a combination of prop() and data(). The latter of which puts the values in to jQuery's cache, not the DOM, which gives better performance, but requires that you also use data() as a getter to retrieve the values:
$(".test").prop('id', '/dam/pic.jpg').data({
'asset-share-id': 'asset',
'asset-share-asset': '/dam/pic.jpg'
});
You can use following logic using split() and attr() methods
$(function(){
var assetHtml='data-asset-share-id="asset" data-asset-share-asset="/dam/pic.jpg" id="/dam/pic.jpg"';
var assetAttr = assetHtml.split(' ');
for(var i=0; i<assetAttr.length; i++) {
var attr = assetAttr[i].split('=');
$( ".test" ).attr(attr[0], attr[1]);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<article class=test> Article<article/>
I recognise that the question asks for a solution using the jQuery library but for the sake of completeness, here, additionally, is a solution using vanilla javascript.
Working Example:
// GET THE ARTICLE ELEMENT
const testArticle = document.getElementsByClassName('test')[0];
// CREATE OBJECT CONTAINING ATTRIBUTES AND VALUES
const assetHtml = {
'data-asset-share-id' : 'asset',
'data-asset-share-asset' : '/dam/pic.jpg',
'id' : '/dam/pic.jpg'
}
// GET THE ATTRIBUTES (ie. THE KEYS OF THE OBJECT ABOVE)
const assetHtmlAttributes = Object.keys(assetHtml);
// ASSIGN ATTRIBUTES AND VALUES TO THE ELEMENT
assetHtmlAttributes.forEach((attribute) => testArticle.setAttribute(attribute, assetHtml[attribute]));
// VIEW UPDATED ELEMENT
console.log(testArticle);
<article class="test"></article>

setting color of a link in javascript

I want to set the color of "val" in the link in below code.
var link = $('' + val + '<br><br>');//this is the link
link.style.color="red";//this is how iam trying to set the color of "val"
SO HOW TO EXACTLY DO IT.
You can do this:
link.css({ color: 'red' });
But the correct and nice way would be:
$(".parent_element").prepend(''+val+'<br><br>');
$(".parent_element > a:first").css({ color: 'red' });
Try this:
$(link[0]).css({ color: 'red'});
The reason for this is that link is not an <a> element - it's a set of elements: <a>, <br> and another <br>.
Another approach would be:
link.css({ color: 'red' });
but this will set this CSS to not only <a>, but both <br>'s as well (not a big deal though).
If you are using jQuery(which it does seem like) go ahead with this,
jQuery
link.css("color","red");
Otherwise,
JavaScript
link[0].style.color = "red";
What you did doesn't work because link is an array. Before applying a style to it, you have to first select the first element by link[0] and then operate on it.
You could use link.style.color="red" if link was an HTMLElementNode, but it isn't. It might be a jQuery object, but if you are using an older version of the library then it will return undefined.
First you need to fix your jQuery call. You can't create multiple elements at the top level. (You can skip this bit if you are using a sufficiently new version of jQuery).
Since there is no good reason to use a double <br> (it shouts "Use CSS to add a margin instead"), I've taken them out:
var link = $('' + val + '');
Now you have a jQuery object so you can either use the jQuery method of setting CSS:
link.css("color", "red");
or get the HTMLElementNode from the jQuery object and use that:
link.get(0).style.color="red";
link.css("color", "red")
However, I think it would be better to create a css class for that and set up the color there. In Javascript/jQuery I would just add the class to the tag when needed. It is more elegant.

Use getElementById() on non-current HTML document

Essentially, I want to pull text within a div tag from a document on my server to place it in the current document. To explain the reason: I want to pull a headline from a "news article" to use it as the text for a link to that article.
For example, within the target HTML is the tag:
<div id='news-header'>Big Day in Wonderland</div>
So in my current document I want to use javascript to set the text within my anchor tags to that headline, i.e.:
<a href='index.php?link=to_page'>Big Day in Wonderland</a>
I'm having trouble figuring out how to access the non-current document in JS.
Thanks in advance for your help.
ADDED: Firefox style issue (see comment below).
I'm not sure where you're getting your HTML but, assuming you already have it in a string, you could create a document of your own, stuff your HTML into it, and then use the standard getElementById to pull out the piece you want. For example:
var doc = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null);
doc.documentElement.innerHTML = '<body><div>Nonsense</div><div id="news-header">Big Day in Wonderland</div><p>pancakes</p></body>';
var h = doc.getElementById('news-header');
// And now use `h` like any other DOM object.
Live version: http://jsfiddle.net/ambiguous/ZZq2z/1/
Normally, I would try to solve an issue only with the tools specified by the user; but if you are using javascript, there really is no good reason not to just use jQuery.
<a id='mylink' href='url_of_new_article' linked_div='id_of_title'></a>
$(function() {
var a = $('#mylink');
a.load(a.attr('href') + ' #' + a.attr('linked_div'));
});
That little function up there can help you update all your link's text dynamically. If you have more than one, you can just put it in a $('a').each() loop and call it a day.
update to support multiple links on condition:
$(function() {
$('a[linked_div]').each(function() {
var a = $(this);
a.load(a.attr('href') + ' #' + a.attr('linked_div'));
});
});
The selector makes sure that only the links with the existence of the attribute 'linked_div' will be processed.
You need to pull the content of the remote document into the current DOM, as QuentinUK mentioned. I'd recommend something like jQuery's .load() method

How to get the innerHtml, including the tag, using jQuery?

Sorry, if the title is too obscure ;D.
Actually the problem is, lets say i am this code.
<span id="spanIDxx" style="blah-blah">
<tag1>code here </tag2> sample text
<tag2>code here </tag2> html aass hhddll
sample text
</span>
Now if i will use the code.
jQuery("#spanIDxx").html();
then it will return just the innerHTML excluding <span id="spanIDxx" style="blah-blah">
but i want something which can return the innerHTML including the specified element.
This will create a new div and append a clone of your element to that div. The new div never gets inserted into the DOM, so it doesn't affect your page.
var theResult = $('<div />').append($("#spanIDxx").clone()).html();
alert( theResult );
If you need to use this frequently, and don't want to bother with adding yet another plugin, just make it into a function:
function htmlInclusive(elem) { return $('<div />').append($(elem).clone()).html(); }
alert( htmlInclusive("#spanIDxx") );
Or extend jQuery yourself:
$.fn.htmlInclusive = function() { return $('<div />').append($(this).clone()).html(); }
alert( $("#spanIDxx").htmlInclusive() );
You can copy the node to a new empty node, ask for new .parent() and then its .html()
Clone might be useful to you. I don't believe you actually need to do anything with the clone/s.
Haven't used this myself but looks like it may be of use:
http://yelotofu.com/2008/08/jquery-outerhtml/
demo here: http://yelotofu.com/labs/jquery/snippets/outerhtml/demo.html

Categories