JQuery - get attr/text from HTML string in a variable - javascript

I have a HTML string that I'm passing through a function and I want to be able to perform Jquery methods on that variable from inside the function - such as .attr('href') or .text(). I'm sure there is a simple solution for this and something more elegant then temporarily appending the DOM.
HTML
<div class="here"></div>
Javascript
link = 'Google';
// This works
$('.here').html(link);
works = $('.here').text();
console.log(works);
// This doesn't
not = link.text();
console.log(not);
http://jsfiddle.net/dfgYK/

You need to create a jQuery object from link in order to use jQuery methods on it. Try:
not = $(link).text();
DEMO: http://jsfiddle.net/dfgYK/1/
Depending on what you're doing with link, it might be beneficial to do this earlier in your code so that you can just use something like:
var $link = $(link);
console.log(link.text());

You can make a jQuery object that is not part of the DOM by passing a string in:
link = $('Google');
Then, jQuery methods will work on it:
var text = link.text();

Create the link with jQuery instead:
var link = $('<a />', {
href: "http://www.google.com",
text: "Google"
});
Then you can access it's properties with link.text() like you wanted.

Related

.addClass() not working

This is my first time working with .addClass().
In my project, I need to display notifications on a dummy phone screen (an image of iPhone). A notification has a title and some description. This title and description is coming from a form on the same webpage. To compose this notification, I am doing:
var notificationText = $('#title').val().addClass('title') + plainText.addClass("description");
However, I am getting an error:
TypeError: $(...).val(...).addClass is not a function
What am I doing wrong here?
UPDATE:
So, as per the overwhelming requests, I did:
var notificationText = $('#title').addClass('title').val() + plainText.addClass("description");
However, I am getting an error:
Uncaught TypeError: Object sss has no method 'addClass'
jsFiddle
UPDATE 2: I do not need to style the description, so I removed the class related to it. Please see my updated fiddle. Now the problem is that the text in title is getting bold instead of the one copied in #notifications. It is not getting styled as per the CSS.
So many answers in so little time... sigh
I gathered what I think you wanted. Try this one:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/7b3j2/13/
$(document).ready(function(){
CKEDITOR.replace( 'description' );
$('#title').focus();
$('form').submit(function(event){
event.preventDefault();
var html=CKEDITOR.instances.description.getSnapshot();
var divEle=document.createElement("DIV");
divEle.innerHTML=html;
var plainText=(divEle.textContent || divEle.innerText);
var $title = $('<span></span');
$title.addClass('title');
$title.text($('#title').val());
var $desc = $('<span></span');
$desc.addClass('description');
$desc.text(plainText);
$('form').append($title);
$('form').append($desc);
});
});
You can obviously chain some of the span operations, but I left them readable for now. Shorter version would look like:
var $title = $('<span></span').addClass('title').text($('#title').val());
var $desc = $('<span></span').addClass('description').text(plainText);
$('form').append($title).append($desc);
As you probably know by now, but for completeness, the initial errors were the result of trying to apply jQuery methods to string objects. This solution creates new jQuery span objects that can then be styled and appended to the form.
You are trying add class to a value, which is definitely is not a jQuery object
Try this instead:
$('#title').addClass('title').val()
addClass can only be performed on jQuery objects and returns a jQuery object - that's what makes it chainable. You can't add a class to a string.
So, in this code, there are actually two mistakes:
1) plainText.addClass - plainText is a string, and not a jQuery object. You must add the class to the element you created (in your case, the divEle element), but, since addClass only works with jQuery objects, you must convert your div to a jQuery element first. You can accomplish this by doing the following:
$(divEle).addClass('description');
2) addClass returns a jQuery object, so you can't concatenate it with a string.
EDIT: Just realized that you're appending notificationText (which is a string) to the DOM. You must convert it to a div and add the div to the DOM.
jsFiddle: http://jsfiddle.net/7b3j2/17/
Mistake done by you:
<div id="title"><div>
$('#title').val().addClass('title')
->Now here $('#title').val() will give that particular element value.
->$('#title').val().addClass() you are adding class to that value.
Use this:
$('#title').addClass();
As you cannot add class to element's value.
You should addClass to particular element as addClass internally will add attribute class to that element.
So finally solution becomes:
$('#title').addClass('title').val()
For adding a class, you have to use
$('#title').addClass('title');
If you want to get the value, you can use
$('#title').addClass('title').val()
While addClass and val() are both methods on the jQuery object, val() is not chainable like addClass is. When you do $('#title').val() you aren't returning the object, you're only returning the string value of the element.
Use this instead:
$('#title').addClass('title');
And if you still need to get the value:
$('#title').addClass('title').val();
The reason why plaintext is producing an error is because you're trying to use the jQuery addClass method on a DOM node that has been natively created with document.createElement("DIV");. This will not work. To get it to work you either need to to define your new element with jQuery:
var divEle = $('<div></div>');
and then add the class:
divEle.addClass('description');
Or use the native classname method to add the class to the DOM node:
divEle.className = divEle.className + " description";
Try putting addClass first
$('#title').addClass('title');
Update
To get the code fully working you should split up the line like so.
var notificationText = $('#title').val() + ' ' + plainText;
$('#title').addClass('title');
$(plainText).addClass("description");
Fiddle
Final Update
So what we actually want to do here is:
get the values of the content
append them on submit and style the appended text
Example
// Get the text.
var notificationText = $('#title').val() + ' ' + plainText;
// Append to form.
$('form').append('<span class="summary">' + notificationText + '</span>');
// CSS styling
.summary {
display:block;
font-weight: bold;
}
See Fiddle
Considering #title is the id of the element.
You can directly need to add classname to it.
$('#title').addClass('className');
where className is the name of the class.
because you are trying to add class over value instead of element.
$('#title').val().addClass('title') //it is wrong
replace it with:
$('#title').addClass('title')
if plainText is not an element object you initialize by
var plainText = $('#anotherId');
will also cause this error.

Passing a JS variable to getElementById

I am working on a small website where I want to switch tabs based on the variable passed in the URL. Here's the logic I have currently written.
var hash = window.location.href.split("#");
var count = hash.length;
if(count > 0){
var blockid = hash[1];
document.getElementById(hash[1]).css("display","block");
//document.getElementById("showthisdiv").css("display","block"); - this works
document.getElementById("broken_href").innerHTML = blockid;
}
<div class="broken_href"> </div>
hash[1] is the name of the div that I want to change the style of. If I change the hash[1] and write the name of the div in the GetElementById it works fine.
Also just to test i created a dummy div to see what value was being held by the blockid. It is passing the value correctly.
URL for testing would be something like:
http://localhost/test/#showthisdiv
What do i need to do to solve this?
This row is your problem
document.getElementById(hash[1]).css("display","block");
This .css method is a jQuery method and is not available in basic Javascript.
You could use:
document.getElementById(hash[1]).style.display = "block";
Or include jQuery and use:
$("#"+hash[1]).css("display","block");
You are trying to use css jquery method on DOM node, not on jq object
Use that instead:
$('#'+hash[1]).show();
Use
var hash = window.location.hash;
and then
document.getElementById(hash.substring(1)).style.display = "block";
If you use jQuery you can do this directly:
var hash = window.location.hash;
...
$(hash).show();
window.location.hash returns a value like this: #some-hash. This is the reason for what you need to use substring(1) when calling getElementById.

Adding custom data attribute for a new node in Jquery does not work

I tried to use the method data (jQuery 1.7.1) in this code:
var q = '<div class="form-error-marker"></div>';
var t = $(q).data('message', message).insertAfter(el);
and it does not work.
Note that this works:
var t = $(q).attr('data-message', message).insertAfter(el);
Why does the first variant not work?
EDIT: insertAfter works correctly and new div is added after el (which is instance of one element which I get by getElementById() function; long story short I have a library that I extend).
When I say 'it does not work' I mean that the attribute 'data-message' is not stored.
Using data like that sets an arbitrary piece of data for this node; it doesn't add a new data- attribute. Just add the attribute with the attr function, and then access it with data
var q = $('<div class="form-error-marker"></div>').attr("data-message", message);
Now access it like this:
var message = q.data("message");
Here's a fiddle
When you use jQuery.data you don't change element attributes, instead your data saved in $.cache.
So if you want to change element attributes use jQuery.attr, when you want to save some info use jQuery.data

jquery DOM object custom variable atribute inside it

jQuery('<div/>', {
id: 'karta'+i,
znak: player1
}).appendTo('#igrac1');
znak:player1 one is the way that i tried to make custom atribute inside that object, but its wrong. So is it possible to have custom atribute inside jquery object ?
As others have said, when using jQuery, it's much safer to use .data() to store custom data on an element. You can do that compactly in your example like this:
jQuery('<div/>', {id: 'karta'+i,}).data("znak", player1).appendTo('#igrac1');
And, then when you want to reference the znak data, you get it with this:
var curPlayer = jQuery("#karta1").data("znak");
You can see it work here: http://jsfiddle.net/jfriend00/fqaKg/
If you want to set multiple data items on an object, you can do it either with multiple .data() calls or by passing an object to .data():
jQuery("#karta1").data("player", "Bob").data("age", 13);
or
jQuery("#karta1").data({player: "Bob", age: 13});
And, those can then be retrieved as:
var player = jQuery("#karta1").data("player");
var age = jQuery("#karta1").data("age");
Look at the jQuery.data() function, maybe you can use it in your case. Here is a fiddle with an example i've just made: http://jsfiddle.net/dRtqQ/
Here is the html:
<div id="igrac1"></div>
Here is the Js:
jQuery('<div/>', {
id: 'karta',
znak: 'hey'
}).appendTo('#igrac1');
var igracDiv= $("karta");
// store the information
jQuery.data(igracDiv, "test",{name:"Joe", age:12});
//then to read it (or put it in another variable)
alert(jQuery.data(igracDiv, "test").name);
If I'm understanding what you're trying to do, you need to use attr:
http://jsfiddle.net/HGz7D/
var newDiv = jQuery('<div/>', {
id: 'karta'
}).attr(znak,player1)
or you could do this:
var details = {
id: 'karta'
};
details[znak] = player1;
var newDiv = jQuery('<div/>', details).appendTo('body');
But as stated in the other question, data is usually a better idea than custom attributes.
You're setting an attribute znak to the value of player1. In other words the element would look like this
<div id="kart1" znak="<!-- value of player` -->"></div>
You might be looking for $.data to store a value for the element.

Can I get a jQuery object from an existing element

I have a function
function toggleSelectCancels(e) {
var checkBox = e.target;
var cancelThis = checkBox.checked;
var tableRow = checkBox.parentNode.parentNode;
}
how can I get a jQuery object that contains tableRow
Normally I would go $("#" + tableRow.id), the problem here is the id for tableRow is something like this "x:1280880471.17:adr:2:key:[95]:tag:". It is autogenerated by an infragistics control. jQuery doesn't seem to getElementById when the id is like this. the standard dom document.getElementById("x:1280880471.17:adr:2:key:[95]:tag:") does however return the correct row element.
Anyways, is there a way to get a jQuery object from a dom element?
Thanks,
~ck in San Diego
Absolutely,
$(tableRow)
http://docs.jquery.com/Core/jQuery#elements
jQuery can take the DOM elements, try with:
$(tableRow)
or
$(checkBox.parentNode.parentNode)
You should be able to pass the element straight in, like this:
$(tableRow)...
I have tested this by creating a reference to a div, then passing it straight into jQuery and it creates the jQuery object for you.
You can call the jQuery function on DOM elements: $(tableRow)
You can also use the closest method of jQuery in this case:
var tableRowJquery = $(checkBox).closest('tr');
If you want to keep using your ID, kgiannakakis (below), provided an excellent link on how to escape characters with special meaning in a jQuery selector.
See this for how you should escape the id.
try:
var r = $(document.getElementById("XXXX----ID Of Your Row----XXXX"));
now, if document.getElementById doesn't return undefined you can use r as any regular jquery object.

Categories