SOMEUSERNAME
<div class="col s9">
<p id="p_50">Some message</p>
<br>
<br>
<span class="forumtools">
<strong>
<a onclick="quote(\'p#p_50\')">Quote</a>
</strong>
<span class="right">Written SOMEDATE</span>
</span>
</div>
JQuery/JS:
function quote(post) { $(post).text(); }
This works to fetch the posts message, but how do I go about finding the Username?
I have tried using $(post).prev('a').text();, and $(post).parent().prev('a').text();, but nothing seems to work.
You can do it without jQuery. If possible, change the html and pass the current link to the function, like this:
<a onclick="quote(\'p#p_50\', this)">Quote</a>
Then you can just search through all links:
function quote(str, currentLink) {
var allLinks = document.getElementsByTagName("a"); // get all links in document
var index = allLinks.indexOf(currentLink);
if (index > 0) {
var prevLink = allLinks[index-1];
console.log(prevLink); // log it to browser console
} else {
console.log("there is no previous link");
}
}
By looking at the DOM structure, it should work with $(post).parent().prev().text().
Alternative way, how about you wrap all of them with <div>, like this: XD
<div id="message1">
SOMEUSERNAME
<div class="col s9">
<p id="p_50">Some message</p>
<br>
<br>
<span class="forumtools">
<strong>
<a onclick="quote(\'#message1\')">Quote</a> //change to wrapper id
</strong>
<span class="right">Written SOMEDATE</span>
</span>
</div>
</div>
then to get the post text: $(post).find('#p_50').text();
to get the username: $(post).find('a:first').text();
Looking at your sample HTML, if you're at p, just go to parent element and get the closest a and you should be fine:
function quote(post) {
var post = $(post).text();
var user = $(post).parent().closest('a').text();
}
Perhaps using parent() and then previous()
var ancortext = $(post).parent().prev().text();
A function example below.
function username(post) {
return $(post).parent().prev().text();
}
Note: This smells to me, your code is very much tied into the structure of the HTML this way. If you alter the HTML, chances are your javascript will break.
I have copied your code into my own HTML document, and confirmed that the jquery method calls above output the desired result. If you are not, then something is different with your source HTML and the source that you posted, or your jquery functions differ from the ones stated in this answer :)
your onclick attribute is wrong,because onclick accept javascript,so the value could be support js,then onclick="quote('p#p50')".
function quote(post) {
var subject = $(post).text();
var user=$(post).parent().prev('a').text();
console.log('posted '+subject+' by '+user);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
SOMEUSERNAME
<div class="col s9">
<p id="p_50">Some message</p>
<br>
<br>
<span class="forumtools">
<strong>
<a onclick="quote('p#p_50')">Quote</a>
</strong>
<span class="right">Written SOMEDATE</span>
</span>
</div>
Related
I'd like to have basic code like the following:
<span onmouseover="alert('hi')">Hello, <span onmouseover="alert('hello')">this</span> is a test</span>
However, I'd like to keep it from firing both of these events if both are being hovered over; e.g. if I hover over "this" it should fire only its event and alert "hello." How can I do this?
Thank you in advance!
$(".container").hover(function(){
alert($(this).attr("id"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="container" id="hi">
Hello,
</span>
<span class="container" id="hello">
this
</span>
<span class="container" id="hi">
is a test
</span>
I am going to assume that the overlapping elements are not the same size. I.e one is bigger than the other.
HTML and inline js:
<span class="container" id="hi">
Hello,
</span>
<span class="container " id="hello">
this </span>
<script>
var hello =
document.getElementById("hello");
var this =
document.getElementById
("this");
hello.addEventListener("click
",pop("hello"));
this.addEventListener("click",pop(" hi");
function pop(string) {
window.alert(string);
}
<\script>
That being said very little is mentioned about the nature of the elements this and hello. Op plz show your CSS and update ques
Here's the relevant portion of what I ended up using. I used JQuery.
var mouseHovered = function(element) {
//get all hovered spans
var hoveredElements = $("span:hover");
//get the element with the smallest text
var smallestElement;
for(var i=0; i<hoveredElements.length; i++) if(!smallestElement || hoveredElements[i].textContent.length < smallestElement.textContent.length) smallestElement = hoveredElements[i];
//if this is the smallest text in the elements
if(element == smallestElement) {
//log the text
console.log(element.textContent);
}
}
You need to prevent Event bubbling when you hover/click on inner span.
This can be done using event.stopPropagation().
Look at two solutions provided at this JSFiddle.
Solution 1 - Use of e.stopPropagation() in the handler function innerSpan().
Solution 2 - Use of event.stopPropagation() in inline onclick event.
<span onclick="alert('Outer span');">
Outer
<span onclick="event.stopPropagation(); alert('Inner span');">
Inner
</span>
</span>
I'm trying to retrieve the ID of one element, store it as a variable and then use that ID value to interact with other elements in that section with the same ID.
<div class="mainContent">
<div class="articleContent">
<h1>header1</h1>
<p class="articlePara" id="one">para1</p>
</div>
<div class="articleFooter" id="one" onclick="readMore()">
</div>
</div>
<div class="mainContent">
<div class="articleContent">
<h1>header2</h1>
<p class="articlePara" id="two">para2</p>
</div>
<div class="articleFooter" id="two" onclick="readMore()">
</div>
</div>
And then the JS/jQuery
function readMore() {
var subID = event.target.id;
var newTarget = document.getElementById(subID).getElementsByClassName("articlePara");
alert(newTarget.id);
}
At this point I'm only trying to display the ID of the selected element but it is returning undefined and in most cases people seem to notice that jQuery is getting confused because of the differences between DOM variables and jQuery ones.
jsfiddle: https://jsfiddle.net/dr0f2nu3/
To be completely clear, I want to be able to click on one element, retrieve the ID and then select an element in the family of that clicked element using that ID value.
just remove the getElementsByClassName("articlePara"); in end of the newTarget .already you are call the element with id alert the element of the id is same with target.id
function readMore() {
var subID = event.target.id;
var newTarget = $('[id='+subID+'][class="articlePara"]')
console.log(newTarget.attr('id'));
console.log(newTarget.length);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mainContent">
<div class="articleContent">
<h1>header</h1>
<p class="articlePara" id="one"></p>
</div>
<div class="articleFooter" id="one" onclick="readMore()">click
</div>
</div>
As you have read before, you should keep your id's unique, and you should avoid using onclick in html, but you could do it like this.
With querySelector you get the element and then with parentElement you can retrieve the parent of that element.
function readMore(el) {
var articleFooterId = el.id;
var articlePara = document.querySelector(".articleContent #"+articleFooterId);
var articleContent = articlePara.parentElement;
console.log('articleFooter', articleFooterId);
console.log('articlePara', articlePara);
console.log('articleContent', articleContent);
}
In your html you can return the 'this' object back to the function by doing readMore(this).
<div class="mainContent">
<div class="articleContent">
<h1>header1</h1>
<p class="articlePara" id="one">para1</p>
</div>
<div class="articleFooter" id="one" onclick="readMore(this)">footertext</div>
</div>
<div class="mainContent">
<div class="articleContent">
<h1>header2</h1>
<p class="articlePara" id="two">para2</p>
</div>
<div class="articleFooter" id="two" onclick="readMore(this)">footertext</div>
</div>
jsfiddle
if you're using Jquery:
$(function () {
$('div.articleFooter').click(function () {
var para = $(this).prev().find('p.articlePara').text();
alert('T:' + para);
});
})
$('.articleFooter').click(function() {
var b=subId; //can be any
var a="p[id="+b+"]"+"[class='articlePara']";
$(a).something;
});
You have forgotten to pass in event as parameter in your onclick= call in html.
In your javascript, you need to include event in the parenthesis as well.
window.readMore = function(event) {...}
if you write document.getElementById(subID).getElementsByClassName("articlePara"); That's saying you want to get your clicked element's CHILD elements that have class equal to articlePara . There is none. So you get undefined.
If you want to find all element with a ID one and a class articlePara, it can be done easily with jQuery:
newtarget = $("#one.articlePara");
You can insert a line: debugger; in your onclick handler function to trigger the browser's debugging tool and inspect the values of variables. Then you will know whether you are getting what you want.
My HTML looks like this:
<div class="col-md-2" id="myName1">
<p>
Get This Text
</p>
</div>
The question is how do I get the text "Get this Text"
Something like this, but getting that text which is wrapped in the p and a tags:
function () {
return document.getElementById('TextID');
}
You can search for the first p inside your myName1 element, then the first a within that.
var e = document.getElementById('myName1').
getElementsByTagName('p')[0].
getElementsByTagName('a')[0];
var theText = e.innerHTML;
console.log(theText);
// or, in sufficiently-modern browsers
e = document.querySelector('#myName1 p a');
theText = e.innerHTML;
console.log( theText );
<div class="col-md-2" id="myName1">
<p>
Get This Text
</p>
</div>
Try adding the following in your function:
return document.querySelector('#myName1 p a').innerHTML
Simply using document.getElementById('anchorID').text; assuming anchor has id of anchorID. The text property sets or returns the text content of a link.
EDIT 1 : If you are not able to add the ID, then you need to take long path by going to document.getElementByID and then reach to the element using the document.getElementsByTagName
var myAnchor = document.getElementById("myName1").getElementsByTagName('p')[0].getElementsByTagName('a')[0];
console.log(myAnchor.text);
<div class="col-md-2" id="myName1">
<p>
<a id="anchorID" href="/something/121212">Get This Text</a>
</p>
</div>
you can use the get element by tag name method, but it returns an array of results so you will have to consider that, in your example, this works...
var a=document.getElementById('myName1');
console.log(a.getElementsByTagName('p')[0].getElementsByTagName('a')[0].innerHTML);
<div class="col-md-2" id="myName1">
<p>
Get This Text
</p>
</div>
Check this code, you can use innerHtml attribute
<script>
function gettext()
{
return document.getElementById('link').innerHTML;
}
</script>
<div class="col-md-2" id="myName1">
<p>
Get This Text
</p>
</div>
<script>
alert(gettext());
</script>
Or if you are using JQuery
$("#myName1 p a").text();
im trying to get a javascript onclick to work the plan is when the user clicks a div with the class="store box" it will echo the which is within that div see example:
<div
onclick="javaclick()"
data-type="store"
class="store box"
data-latitude="53.7658344"
data-longitude="-2.6646485">
<p>
<span class="title" data-type="title">Store38</span>,<br>
<span data-type="address"><i class="fa fa-map-marker"></i> 123 Barrington Road, Barrington, BR1 2JH</span>,<br>
<span data-type="phone"><i class="fa fa-phone"></i> 00000 000000</span><br>
<span data-type="openingtimes"><i class="fa fa-clock-o"></i> Opening Times: <?php include('store-hours.php'); ?></span>
<br>
<span data-type="directions" class="directions">
<label data-type="directions-label">Get directions</label>
<input data-type="directions-input" type="text" class="hidden" />
</span>
</p>
so when the user clicks the div in this case store38, it will write the address from data-type address in the div footer_box.
<div id="footer_box">
<script type="text/javascript">
function javaclick(){
document.write("data-type='address'");
}
</script>
</div>
and it would do it for each of the stores i have 50 in total. any ideas?
Best way to outputting data from JS is to write it into some div.
<div id="Output"> </div>
jQuery function
$("#output").text("works");
Or pure JS solution
document.getElementById("output").innerHtml = "works";
To get that data you will need jquerys .data() or .attr() function:
var data = $(element).data("type");
Or:
var data = $(element).attr("data-type");
To handle it in function, you must transfer element variable.
function javaclick(element) {
}
And bind event:
$(".store").bind("click", function(event){
/* code */
});
Now just assemble that, and you have got solution.
$('.store.box').click(function() {
var data = $(this).data("type");
$('#footer_box').text(data);
});
With jquery, you can do something like this:
$(".store").click(function(){
address = $(this).find('[data-type=address]').text();
$("#footer_box").html(address);
});
Demo Fiddle here
Instead of invoking some javascript from HTML, contain that logic in your JS instead. Example:
(function() {
var footerBox = document.querySelector('footer_box');
[].forEach.call(document.querySelectorAll('.store.box'), function(el){
el.addEventListener('click', function(e) {
footerBox.innerHTML = e.target.dataset.type;
}, false);
});
})();
i m working on adding a FB share button to all my posts.
so i wanted to use the sharer.php? method with all the parameter retrieved from the post.
So my blog structure
<div id='postwrapper'>
<div id='title'>
hello</a>
</div>
<div id='da'>
<span>Posted on </span>
<span class='divider'></span>
<span>By</span>
</div>
<div class='post_content'>$row['post'] gud day</div>
<div id='post_footer'>
<a href=viewpost.php>Continue reading</a>
<a href='#' onClick='fbshare(this)'>Insert text or an image here.</a>
</div>
</div>
My javascript for fbshare function (not complete).
function fbshare(fb) {
var p1 = fb.parentNode;
var p2 = p1.parentNode;
var title = p2.getElementById("title").innerHTML;
alert(title);
}
Everytime i try this it says undefined is not a function
getElementById is a function of the document. Assuming you have more than one post on the page (ids must by unique), try using a class instead:
<div class='title'>
And using getElementsByClassName:
var title = p2.getElementsByClassName("title")[0].innerHTML;
http://jsfiddle.net/AJ9uj/