I've just started using jQuery, but am a bit stuck. I am building a table dynamically in Javascript and am adding classes all the time to cells (for styling), so I would like to use the addClass function:
var row = table.insertRow(-1);
var cell = row.insertCell(0);
cell.addClass('boldRow');
but this does not work. I know you can use the magic $('') function to be able to use jQuery, but can I use it on 'native' HTMLElement references?
$(cell).addClass should do the trick - why don't you try it and let us know.
In any case you have to use the $() to load the jQuery framework to get access to addClass.
You just place the element in like you would a string.
$(someElementReference).addClass('boldrow');
You can also pass in a collection of elements if that is what you have.
Here's an example: http://jsfiddle.net/qS473/
Yes, you can pass in native DOM objects into the jQuery function, and it will create a jQuery object from the DOM object:
$(cell).addClass('boldRow');
But you don't need jQuery to add a CSS class to a DOM object!:
cell.class += ' boldRow';
Yes, you can select all HTML elements with $() for example, $('body'), or $('html') etc. Since it's only a framework, you can also use any other Javascript you can think of to fix this.
Usually the first thing I do when creating a new element is something like this:
var newDivJQObject = $(document.createElement('div'))
.attr('id', '[uniqueID]')
.addClass('[className]');
Related
I know how to do the opposite. Getting a certain DOMElement for a jQuery element is easy. (Use the get() method)
But how can you get a jQuery element for a specific DOMElement?
Unfortunately this DOMElement does not have any attributes like class or id so constructing a selector is not really an option.
Lets say I have this html:
<div class="edit">Abcd<b><i><u>asdasd</u>adasda</i></b>sdfsdf<br>asd</div>
I am in the u-DomElement. How can I get this as a jQuery element?
Is there a smart way to do this?
EDIT:
I wanted to know if there is a gerneral way to do this. Not specific to the code shown above.
Like:
DomElement.toJQuery()
Is there anything like that? I am aware that this might not be possible.
Getting a jQuery object for a DOM object is as simple as jQuery(dom_node) (or $(dom_node)). See http://api.jquery.com/jQuery/
This is commonly used in event handlers, which are given the DOM node as this, so that you will often see $(this)
If you want to get just the Element use the below code. if you wanted to get the HTML of any element you might want to add the .html() tag to either of the examples
var myVar = $('.edit u');
or
var myVar = $(".edit").find("u");
Are you looking for this?
$(".edit").find("u");
hope this is what you are looking for,
$(DomElement)
you want a only 1 specific dom element i suggest you find a way to add an id to that element.
but to get an u element inside a edit class:
$('.edit u');
$('.edit').find('u');
here is my html codes where I want to change.
<table>
[some table row]
<tr class="high">
some text
</tr>
[many more table row]
</table>
now I want to remove the following tag with its class and inner contents.
is there any way to remove it using replace command like "replace(/pattern/, '')".
please write a little details about how you write the patterns.
If your table have an id, say table_id you can do it by pure javascript,
var table = document.getElementById('table_id');
for(var i=0; i<table.rows.length;i++){
if(table.rows[i].className=="high"){
table.deleteRow(i);
break;
}
}
You might want to take a look at the jQuery library.
It offers a lot of ways to search and alter html code.
You can search for css patterns and remove the element:
jQuery("tr.high").remove();
http://www.jquery.com
(I'm assuming you're running JavaScript in the browser, since you're dealing with HTML.)
Rather than trying to use regular expressions to parse HTML (which is generally a bad idea), you're probably better off actually building the DOM tree and then traversing it to get the content you need.
For instance, you can put that table in a disconnected div:
var div = document.createElement('div');
div.innerHTML = your_html_string;
...and then use the DOM methods (and possibly innerHTML) and/or a library to get the content you need.
References:
DOM2 Core
DOM2 HTML
DOM3 Core
innerHTML
If you're going to be doing a lot of work in JavaScript on the browser, I recommend using a good JavaScript library like jQuery, Prototype, YUI, Closure, or any of several others. These smooth over browser differences for you and provide a lot of utility functionality so you can focus on the problem at hand.
Why don't you use jquery library.. its simple with that.. This should do the trick
$(document).ready(function(){
$("tr.high").remove();
})
Jquery .remove()
Do you create it like this: $('<div />') or $('<div></div>')
Is that how you create an element? Thanks.
Either way works just fine. Just don't forget to insert in the dom - you can use appendTo(selector).
var $my_elem = $("<div/>").appendTo(document.body);
var $my_elem = $("<div class='abc'></div>").appendTo(document.body);
Then you have $my_elem represending the inserted element.
Looking at the jQuery source code, it looks like anything matching the regular expression /^<(\w+)\s*\/?>(?:<\/\1>)?$/ will be interpreted as a "single tag" and passed directly to document.createElement (assuming no context is specified). Therefore, at least in the current implementation, there's no difference (behavior or performance) between the various formats.
$('YOUR SELECTOR').append('<div />');
The <div /> will create a <div></div>
You can include classes, id's and other attributes, jQuery should figure it out and rap it up.
I included use of the append function because you are probably going to want to insert it somewhere. There is a number of similar functions you could use instead.
I have this line of JavaScript / jQuery that I'm attempting to use to append an element to the DOM and then attach an eventlistener to.
$('.faq_answer').prev().append(finalRender.cloneNode(true)).addEventListener("click", function () {toggle(this)}, false);
I know the appending part works perfectly but adding an event listener is giving me grief.
Is it possible / advisable to use jQuery and normal JavaScript together like this?
Or is there something in jQuery that would work better. (Very new to jQuery so bear with me).
If you want to use the native methods, then you need to call them against DOM elements, not jQuery objects
var clone = finalRender.cloneNode(true);
clone.addEventListener("click", function () {toggle(this)}, false);
$('.faq_answer')
.prev()
.append( clone );
If you want to use jQuery, then you need to wrap the DOM elements in a jQuery object.
// Drop your DOM element----v----into a jQuery object
var clone = $( finalRender.cloneNode(true) ).bind("click", function (){
toggle(this);
});
$('.faq_answer')
.prev()
.append( clone );
You could do something like this:
$('.faq_answer').prev().append(finalRender.cloneNode(true)).click(function () {toggle(this)});
which is pure jquery
I think you're wanting to add your event Listener to the cloned Node - not to the prev() of .faq_answer.
If you're importing jQuery, why not use the .click() method anyway instead of mixing? It's simpler! :)
$('.faq_answer').prev().append(finalRender.cloneNode(true).click(function(){
toggle(this)
}));
Yes, it's possible to use them "together" because jQuery is JavaScript. However in this case there's really no reason to bind event handlers directly like that if you are using the library. It already knows how to manage event handlers, and doing it outside of its control is probably not a good idea unless you really know what you're doing.
I find questions like this are strange, because jQuery is JavaScript.
Based on this mixing up the code that is just plain JavaScript with jQuery code is fine.
But if there is a simpler way of doing what you want in jQuery then I would say to just use jQuery alone.
I have a large Javascript codebase to convert to jQuery. The code is structured such that DOM elements are created in Javascript (using a library called DomBuilder), and saved to variables if they will be needed later, before being added to the DOM.
Eg.
var inputs =
{
submitConfirm: INPUT({type: 'button', value: 'Submit'}),
submitCancel : INPUT({type: 'button', value: 'Cancel'})
};
document.appendChild(inputs.submitConfirm);
Then later for example...
inputs.submitCancel.style.display = 'none';
inputs.submitCancel.addEventListener('click', onClickSubmitCancel, false);
My problem is that jQuery seems to lack a way of manipulating DOM elements directly, as opposed to selecting them first (with for example $('#submitCancel').
Can anyone suggest a way to directly translate the last two Javascript lines given above to use jQuery, given that the DOM elements are already available, and so do not need to be selected?
$(inputs.submitCancel).css('display', 'none');
and
$(inputs.submitCancel).bind('click', onClickSubmitCancel);
See http://api.jquery.com/jQuery/ to see what jQuery accepts.
Any DOM element can be wrapped into a jQuery object very easily:
var myObject = $(domElement)
With myObject you can use jQuery methods.
Use $(elementVar) to get a jQuery object containing the DOM element. For the example you gave:
$(inputs.submitCancel).hide().click(onClickSubmitCancel);