alert the class name of an element using javascript - javascript

i have an element and i want to alert the class attribute of this element i use this code;
<li id="SSS" class="settings" onclick="alertClassName(this)">1111</li>
and in the alertClassName function ;
function changeClass(elem)
{
var x = $(elem.id);
alert(x.class) ;
}
it alerts undefind.

Try with className instead of class.
onclick="alertClassName(this)"
...
function alertClassName(elem) {
alert(elem.className);
}
Reference.

First off, you have to decide on a function name (alertClassName or changeClass). I'll use alertClassName as that matches the question title:
Here:
<li id="SSS" class="settings" onclick="alertClassName(this)">1111</li>
...you're passing a reference to the actual element into your function. The this within the code in an onxyz DOM0 handler attribute refers to the element the onxyz attribute is on.
This means you can just use it directly:
function alertClassName(elem)
{
alert(elem.className);
}
And if you wanted to change it:
<li id="SSS" class="settings" onclick="changeClass(this, 'foo')">1111</li>
and
function changeClass(elem, newClass)
{
elem.className = newClass;
}
...would remove all classes from the element when it was clicked and add the foo class.

You can access class name directly via className property (no need for jQuery, in this case):
function alertClassName(elem)
{
alert(elem.className);
}

You trying to activate different function then what you posted) alertClassName instead of changeClass )
Here's an example of how to alert and then change the class of your element. (here's the fiddle).
And the code:
<li id="SSS" class="settings" onclick="changeClass(this)">1111</li>
<script>
function changeClass(e)
{
alert("Current Class:" + e.className);
e.className = "Settings2";
alert("Updated Class:" + e.className);
}
</script>

try:
alert($(this).attr('class'))

Related

Javascript Class References in Html

Assuming I have a class class FooBar() {} with a method doSomething(){}, can I create and append a html element from within the class itself that calls doSomething() when clicked?. Here is a code snippet:
class FooBar{
constructor(options){this.options = options}
doSomething(){ /* onclick functionality */}
creator(){
let reference = `<div onclick="this.doSomething()"></div>`;
document.getElementByTagName('body')[0].innerHtml = reference;
}
}
I would now like to know the correct way of writing the let reference . . . line.
First, to attach the event listener you can't use innerHTML because onclick="this.doSomething()" in your string won't point to your class. You have to construct the element using document.createElement and append that using appendChild.
Second, when you attach the event listener, make sure the proper this is used (more on that in this other SO question). We'll just use a simple arrow function. We'll also use addEventListener instead of onclick which is more standard:
class FooBar{
constructor(options) { this.options = options; }
doSomething() { /* onclick functionality */}
creator() {
let div = document.createElement("div");
div.addEventListener("click", ev => this.doSomething( /* pass 'ev' here if you want */ ));
// it's ok to use div.innerHTML here to fill out the div instead of createElement/appendChild
document.body.appendChild(div);
}
}
Maybe try using addEventListener instead of using onclick on the tag
let newElement = document.createElement('div')
newElement.addEventListenser('click', () => console.log('clicked'))

Setting html using jQuery on li element results in error

Here is jsfiddle link - http://jsfiddle.net/howg59sg/5/
<div id='test1'>
<ul>
<li id="li1" friendName="foo">test 1</li>
<li id="li2" friendName="bar">test 2</li>
</ul>
</div>
function myclick() {
alert("clicked");
var elemId = "#li1";
var elemCollection = jQuery(elemId);
alert("len = " + elemCollection.length);
if (elemCollection.length) {
var selectedElem = elemCollection[0];
alert("id of the element to work on " + selectedElem.attributes["id"].value);
var stringToReplaceWith = "testing";
alert("friendname = " + selectedElem.attributes["friendname"].value);
//alert("html value of selected elem = " + selectedElem.html());
selectedElem.html(stringToReplaceWith);
} else {
alert("none");
}
}
As you can see, I am trying to update the html content of a li element using jQuery. This results in following error:
Uncaught TypeError: undefined is not a function
I am able to get attributes on this li element but html() setter fails. Even getter fails as well which i have commented out in the code for now...
Does anyone know, What might be wrong here?
Thanks for the help.
You get the error because selectedElem is not a jQuery object.
var selectedElem = elemCollection[0]; <-- gets the DOM node
selectedElem.html(stringToReplaceWith); <-- you treat it as a jQuery object
either use .eq(0) to get the element as jQuery instead of bracket notation and use .attr() to read the attributes Or wrap it with jQuery() or use innerHTML
Your issue is likely with this line:
var selectedElem = elemCollection[0];
That will give you a regular DOM element object instead of a jQuery object. DOM elements don't have the html() function like jQuery objects do. You can replace the whole function with just these lines of code:
function myclick(){
jQuery('#li1').html('testing');
}
The following line returns a native DOM Html element:
elemCollection[0];
If you want the first item in a collection as a jQuery element use first():
elemCollection.first();

How can i get the Id from the next element?

I'm trying to get the ID from the next element, but i get this - "undefined"...
What am i doing wrong?
http://jsfiddle.net/84x9v/
HTML:
<a class="col" onclick="getId()">
<div id="1"><span>1</span></div>
</a>
JavaScript:
function getId(){
var get = $(this).next("div").attr("id");
alert(get);
}
remove the inline js
<a class="col">
<div id="1"><span>1</span></div>
</a>
and use an event handler
$('.col').on('click', function() {
var get = $(this).find("div").prop("id");
alert(get);
});
note that putting a block element inside an anchor generally isn't very good practice, and the div is a child of the anchor, it's not the next sibling.
'cause it's not the 'next' element.
function getId(){
var get=$(this).find("div").attr("id");
alert(get);
)
should work...
You're using jQuery and .next() wrong. Remove the inline event handler, use .find() instead of .next(), and try:
function getId() {
var get = $(this).find("div").attr("id");
alert(get);
}
$('a').click(getId)
jsFiddle example

change div with Javascript

With pure Javascript I want to create a tab effect to toggle content in a div. Content is the name of the class I want to add or remove the second class active from
<script>
function changeClass(element) {
if (classList !=='active') {
element.classList.add('active');
}
else { element.classList.remove('active'); }
}
</script>
<ul>
<li onclick = "changeClass("content")">
The error is that you're not selecting any elements (wonder why nobody caught this), but trying to change the classlist of a string ("content".classList...). Make sure you select the proper element first:
function changeClass(element) {
element = document.getElementsByClassName(element)[0]; // assuming here we're selecting the first one
if (!element.classList.contains('active')) { // had to fix this as variable classList wasn't defined
element.classList.add('active');
}
else {
element.classList.remove('active');
}
}
Also, as #Teemu suggested in comments, but refused to write it, feel free to use element.classList.toggle('active');.
So the whole code should be:
function changeClass(element) {
element = document.getElementsByClassName(element)[0]; // assuming here we're selecting the first one
element.classList.toggle('active');
}
If you want to simply toggle between two classes, you can do something like this:
function changeClass(element) {
element.classList.toggle('Content');
}
Though in this case you've to pass a reference to the element rather than it's className.

how to pass runtime parameters in jquery functions?

I m new to jquery. My requirement is to pass rowid(unique id of each record of a table) in a jquery function. I can get rowid only at runtime. so how can I bind click event to the tag whose id is this rowid.
Upd
Del
$(what to pass here).bind('click',function(ev) {
_operation(para1,para2); // function which is going to perfom action
ev.preventDefault();
return false;
});
get the id , and acording to id do what ever you want
$('a').on('click',function(){
var id = $(this).attr('id');
if(id == //what you want)
{
//function 1
}
else
{
//function 2
}
return false;
});
If there are any similarities between the IDs, you can use one of the attribute selectors such as:
ID contains
$('[id*="something"]')
ID begins with
$('[id^="something"]')
http://api.jquery.com/category/selectors/
A better approach would be to place all of the dynamically named anchors into a container, and then select on that:
<div id="container">
<a ...></a>
<a ...></a>
</div>
Then you would select all the child anchors:
$('#container > a').click(...);
It's hard to find a good selector from so few HTML code. Use a class on your markup if possible:
<a class="roww" href="javascript:void(0)" id="`string(rowid(Gatepass))`">Upd</a>
<a class="roww" href="javascript:void(0)" id="`string(rowid(Gatepass))`">Del</a>
then you can use $('.roww') to query your nodes.
Here's what you can do to get the id from the event handler:
function( ev ) {
//wrap the element with jQ:
var jel = $(this);
//Then access attributes with .attr() getter:
var id = jel.attr('id');
... //do whatever you want now.
... // there's a quicker alternative to get the id without jQuery, simply:
... // var id = this.id
}
if the id comes dynamically from the server, put inside the function the same id + hash for id selctor
$(what to pass here) => $("'#" + string(rowid(Gatepass)) + "'")

Categories