Hello everyone im trying to get the id of a div through a function in javascript like this:
<div id="txtHint" onload="getId(this);"></div>
The function is located just before </body> tag of my html page
function getId(theId) {
var name = document.getElementById(theId);
}
In the body of my html page i have a button:
<button type="button" onclick="alert(getId())">get</button>
I receive an undefined alert on clicking
How do i get the div's id?
Anyone can help?
Though I don't know the use case of this, you can pass the id to the function and return that from the function:
function getId(theId) {
var name = document.getElementById(theId);
return name.id;
}
<div id="txtHint"></div>
<button type="button" onclick="alert(getId('txtHint'))">get</button>
Update: If you want to get all id's by tag, simple pass the tag to the function and get all the id's of those element:
function getId(el) {
var element = document.querySelectorAll(el);
var id = [...element].map(i=>i.id).filter(i=>i);
return id;
}
<div id="txtHint1">First</div>
<div id="txtHint2">Second</div>
<div id="txtHint3">Third</div>
<div id="txtHint4">Fourth</div>
<button type="button" onclick="alert(getId('div'))">get</button>
The way your functions is written the only way is to have global variable
var divId = null;
function getId(div) {
divId = div.id;
}
function getId() {
alert(divId);
}
And here is my suggetions on doing it
First way is to "mark" the div at onload event and get the id of it using this "mark"
function markDiv(thisDiv) {
thisDiv.classList.add('mark')
}
function getMarkedDiv() {
var div = document.querySelector('.mark');
alert(div.id);
}
<div id="Mark" onload="markDiv(this)" class="mark"></div>
<button onclick="getMarkedDiv()">button</button>
Another way is to wrap the button and the div inside one parent
function getMySiblingId(button) {
alert(button.parentElement.firstElementChild.id);
}
<div id="Parent">
<div id="Mark"></div>
<button onclick="getMySiblingId(this)">Button</button>
</div>
Or the easiest way is to wrap button inside the desired div
function getId(btn) {
alert(btn.parentElement.id);
}
<div id="Mark">
<button onclick="getId(this)">Click me</button>
</div>
<div id="Alice">
<button onclick="getId(this)">Click me</button>
</div>
<div id="Charlie">
<button onclick="getId(this)">Click me</button>
</div>
Of course in all this scenarios i didn't assume that you want to get ids of multiple divs
so i remade the code
function divField(theDivFieldId) {
var name = document.getElementById(theDivFieldId);
return name.id;
}
html
<div id="txtHint" onload="alert(divField(this));"></div>
and nothing happens
Related
I'm learning JavaScript and this is a practice scenario for me.
What I have already is a button that clones content, and within that content that has been cloned, there is a button to remove it.
When I click the button that prompts you to remove the content, it removes the first set of content.
What I want to happen is when you click the button that prompts you to remove the content, it removes the content related to that button and nothing else.
This is the CodePen link.
https://codepen.io/JosephChunta/pen/YzwwgvQ
Here is the code.
function addContent() {
var itm = document.getElementById("newContent");
var cln = itm.cloneNode(true);
document.getElementById("placeToStoreContent").appendChild(cln);
}
function removeContent() {
var x = document.getElementById("content").parentNode.remove();
}
// This is for debug purposes to see which content is which
document.getElementById('orderContent')
.addEventListener('click', function(e) {
const orderedNumber = document.querySelectorAll('.thisIsContent');
let i = 1;
for (p of orderedNumber) {
p.innerText = '' + (i++);
}
});
.contentThatShouldBeHidden {
display: none;
}
<div id="placeToStoreContent">
</div>
<button id="orderContent" onclick="addContent()">Add Content</button>
<div class="contentThatShouldBeHidden">
<div id="newContent">
<div id="content">
<p class="thisIsContent">This is a prompt</p>
<button onclick="removeContent()">Remove this</button>
<hr />
</div>
</div>
</div>
When you'r trying to remove by ID, it takes the first ID it finds.
To remove the correct content, send this onclick.
<button onclick="removeContent(this)">Remove this</button>
And handle it in your function:
function removeContent(el) {
el.parentNode.remove();
}
Example:
function addContent() {
var itm = document.getElementById("newContent");
var cln = itm.cloneNode(true);
document.getElementById("placeToStoreContent").appendChild(cln);
}
function removeContent(el) {
el.parentNode.remove();
}
// This is for debug purposes to see which content is which
document.getElementById('orderContent')
.addEventListener('click', function(e) {
const orderedNumber = document.querySelectorAll('.thisIsContent');
let i = 1;
for (p of orderedNumber) {
p.innerText = '' + (i++);
}
});
.contentThatShouldBeHidden { display: none; }
<div id="placeToStoreContent">
</div>
<button id="orderContent" onclick="addContent()">Add Content</button>
<div class="contentThatShouldBeHidden">
<div id="newContent">
<div id="content">
<p class="thisIsContent">This is a prompt</p>
<button onclick="removeContent(this)">Remove this</button>
<hr />
</div>
</div>
</div>
In your remove button, do this:
<!-- The "this" keyword is a reference to the button element itself -->
<button onclick="removeContent(this)">Remove this</button>
And in your javascript:
function removeContent(element) {
element.parentNode.remove();
}
I'm trying to hide a part of every user email, registered in a website.
So lets say I have get zero#example.com and I want to hide everything after the "#". And only show it if someone clicks on whats left of the email.
Any help would be appreciated.
This just hides everything.
<p>
<button onclick=".hide('#email')">Hide</button>
<button onclick=".show('#email')">Show</button>
</p>
<div id="email">
<h2>zero#example.com<h2>
</div>
Try following:
<script type="text/javascript">
function show(){
document.getElementById('trail').style.display = 'inline';
}
function hide(){
document.getElementById('trail').style.display = 'none';
}
</script>
<p>
<button onclick="hide()">Hide</button>
<button onclick="show()">Show</button>
</p>
<div id="email">
<h2>zero<span id="trail">#something.com</span></h2>
</div>
You can use split ( => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split ) if you know what character to expect. In this case:
var full; // let's say, it already has a value (f.e. zero#something.com)
var visiblePart = full.split("#")[0];
and eventually you can do something like this on click:
function show(){
document.getElementById("emailH2").innerHTML = full;
}
function hide(){
document.getElementById("emailH2").innerHTML = visiblePart;
}
and
<h2 id = "emailH2">zero#something.com<h2>
My view has a button and the view is looped.so it has raws.
when i click the button of a single raw i need to color that button.
so i added a onclick="select_Button(<?php echo $rawID?>)" to the raw's button in my view
select_Button is my funtion in js
function select_Button(rawNumberOfVote) {
var RawNumber = rawNumberOfVote;
alert ("Form submitted successfully" + RawNumber);
var upVote = document.getElementById("up_vote");
upVote.style.background = "green";
}
like above i send the rawID to the funtion.
how can i edit this line to accept the view called up_vote in that particular raw id that i got from parameter.
var upVote = document.getElementById("up_vote");
becuz if i only use this line it will color the first raw's button instead the one i wanted
Thank you
you can use data attribute in your html referencing to this page and this page. and retraive with this this jquery code snippet:
$("[data-test ='my value']")
or this code snnipet in javascript:
document.querySelectorAll(".example").find(function(dom){
return dom.dataset.test == "expected-value"
});
Update:
accourding to this page querySelectorAll return nodeList and NodeList are not array and we cannot use find method so I change my answer to this code:
<html>
<body>
<div class="post" data-key="1">
<lable>test</lable>
<button type="button" onclick="upvote(1)">up vote</button>
</div>
<div class="post" data-key="2">
<lable>test</lable>
<button type="button" onclick="upvote(2)">up vote</button>
</div>
<div class="post" data-key="3">
<lable>test</lable>
<button type="button" onclick="upvote(3)">up vote</button>
</div>
</body>
</html>
<script type="text/javascript">
var upvote = function(id) {
var nodes = document.querySelectorAll(".post");
console.log(nodes.length);
for(i = 0 ; i < nodes.length ; i++){
console.log(nodes[i].dataset.key);
if (nodes[i].dataset.key == id)
nodes[i].style.backgroundColor = "red";
}
};
</script>
In html I am having the following tags:
<span id=M26>2011-2012</span>
<div id=c26 STYLE="display:none">
<span id=M27>2012-2013</span>
<div id=c26 STYLE="display:none">
On Clicking on 2011-2012 or on 2012-2013 I want to set display property of div tag.
I am using the following Javascript code for this and I am calling the Javascript function in body tag. The output is showing style and display is not an object or property.
<script language="javascript">
function clickHnadler()
{
var xid= document.getElementsByTagName("span");
var xsp= xid[0].id;
alert("Span id is "+xsp);
if(xsp.charAt(0)=="M")
{
var oC = document.all("C"& xsp.substring(1,2));
if(oC.STYLE.display == "none")
{
oC.Style.Display = "";
}
else{
oC.Style.Display = "none";
}
}
}
</script>
use jquery:
you can pass in the function the element or the Id:
ex:
<span id=M26>2011-2012</span>
function clickHnadler(element)
{
var id = $(element > span).attr(id);
id[0] = 'c'; //not the nicest way, maybe use a replace or something like that
$(id).show(); //or $(id).css('display','list');
}
You may use clickHandler has following way,
function clickHandler(e) {
window.document.links[0].handleEvent(e);
}
You need to bind event spacifically to elements you want to handle click for. for more information please refer following link,
http://docs.oracle.com/cd/E19957-01/816-6409-10/evnt.htm#1009606
Based on what i understand from your question, I come up with this.
<script type="text/javascript" src="jquery1.8.js"></script>
<span id=M26>2011-2012</span>
<div id=c26 STYLE="display:none">
2011-2012 details</div>
<br />
<span id=M27>2012-2013</span>
<div id=c26 STYLE="display:none">
2012-2013 details
</div>
Given the following HTML:
<div class="component">
<div class="component">
<div class="component">
</div>
</div>
<div class="component">
<div class="somethingelse">
</div>
<div class="component">
</div>
<div class="component">
<input type="button" value="Get Path" onclick="showPath(this)" />
</div>
</div>
</div>
I'm trying to write the function showPath so that it returns the index of the parent div in relation to its siblings of class component. So in the above sample, I would like the function to return 1.
I've got this far, but it returns 2; I don't know what to do to ignore the div of class somethingelse
function showPath(element) {
var component = $(element).closest('.component');
alert(component.index());
}
A quick and simple extension for jQ to turn this process into a method:
$.fn.getIndex = function(){
var index = $(this).parent().children().index( $(this) );
return index;
}
Run this on document.ready or wrap it in a function and run it that way (probably cleaner).
Usage is as simple as
var index_for_element = $('.thing-you-want-index-for').getIndex();
Try this(haven't tested):
function showPath(element) {
var component = $(element).closest('.component');
alert(component.parent().find(".component").index(component));
}
You can do this.
$('input').click(function() {
var component = $(this).closest('.component');
alert(component.parent().children(".component").index(component));
})
Check working example at http://jsfiddle.net/Qzk6A/2/