How to call querySelector for different class? [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Need to make a webpart which gets data from API in JSON format. I generate a table from JSON with projects number. Then I change each td to link with class="project_number".
Now each position has it's specific class. No I need each link to direct to project details ot url like: https://XXX.azurewebsites.net/api/protocollines?protocolNo=PR0002
I don't know what parameter should I place in querySelector to have addEventListener for each link.
document.querySelector("???").addEventListener('click', *function*);
function changeToLink(){
var tableCells = Array.from(document.getElementsByTagName('td'));
var i;
var proNo = "PR0";
for (i=0; i<tableCells.length; i++ && isContains == true) {
var proFromArray = tableCells[i].innerHTML;
var isContains = proFromArray.includes(proNo);
if(isContains == true){
var tdElement = document.getElementsByTagName('td')[i];
console.log('Profrom: ' + proFromArray);
tdElement.innerHTML = `<a class="${proFromArray}" href='https://XXX.azurewebsites.net/api/protocollines?protocolNo=${proFromArray}'>${proFromArray}</a>`
}
}
}
document.querySelector(`??`).addEventListener('click', *function*);

There's a few ways to do this.
Option 1
You could create the anchor elements using JS, and add the onclick event when you create each one, like:
// inside the if(isContains == true){
var a = document.createElement('a');
a.className = proFromArray;
a.href = `https://XXX.azurewebsites.net/api/protocollines?protocolNo=${proFromArray}`;
a.textContent = proFromArray;
a.onclick = this.getJsonData;
I created a Fiddle to demonstrate how it works: https://jsfiddle.net/brettnolf/f3xd7ag1/
Option 2
Now, if you need to create it in the form of a string and later call querySelector on what you created, you could add the same class to each anchor tag:
tdElement.innerHTML = `<a class="${proFromArray} pro-elem" href='https://XXX.azurewebsites.net/api/protocollines?protocolNo=${proFromArray}'>${proFromArray}</a>`
Then add the event listener, like:
var pros = document.querySelectorAll('.pro-elem')
for (var i = 0; i < pros.length; i++) {
pros[i].addEventListener(this.getJsonData);
}
Option 3
If both of those solutions are out of the question, you could use a query selector wildcard and add the event listener similar to the above:
var pros = document.querySelectorAll('[class^=PR0]')
// or if you wanted to be really specific:
// document.querySelectorAll('td a[class^=PR0]')
for (var i = 0; i < pros.length; i++) {
pros[i].addEventListener(this.getJsonData);
}
You can see this last solution in action if you pull up Chrome dev tools here https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll and enter document.querySelectorAll('[class^=title]') in the Console.
Note that the last two options will only work after the elements have been added to the DOM. In the first option, you add the listener when you create the element, so you do it on the fly.

Related

How to make expand collaspe and expand to move to top like anchor [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have zero knowledge in JS or JQuery and am learning to do so
I am trying to update my code that will help me do the following
I am trying to achieve the following points, at once :
When you click on the anchor link, the page moves the content to the top of the page.
When you click on the expand for a object, the others collapses
I have finally compiled this code here
Click here to view the link
Please help me in achieving both the points
Thanks for your efforts
You need to modify your collapseExpandLink function like this. I added a For Loop which will loop through all the links and close them all. As for the scrolling, I borrowed a bit of code from user MSolanki's answer. Said method used is ScrollIntoView.
Codepen Example
function collapseExpandLink(evt) {
if (this.collapseDiv.style.display == '') {
this.parentNode.parentNode.nextSibling.style.display = 'none';
this.firstChild.nodeValue = 'expand';
} else {
//Close all DIVs
for(var i = 0;i < collapseLinks.length;i++){
collapseLinks[i].parentNode.parentNode.nextSibling.style.display = 'none';
}
this.parentNode.parentNode.nextSibling.style.display = '';
this.firstChild.nodeValue = 'collapse';
//Scroll page to current clicked link
this.scrollIntoView();
}
if (evt && evt.preventDefault) {
evt.preventDefault();
}
return false;
}
[UPDATED]
You need to add your image with javascript inside the function you use to create all collapsible links.
Updated Codepen example
function createCollapseLink(element, siblingContainer, index) {
var span;
//Create an image element
var img = document.createElement("img");
//Provide image src url
img.src = "http://www.webster.ch/_resources/images/down-arrow.png";
//Add classname
img.className = "myImg"
if (document.createElement && (span = document.createElement('span'))) {
span.appendChild(document.createTextNode(String.fromCharCode(160)));
var link = document.createElement('a');
link.collapseDiv = siblingContainer;
link.href = '#';
//Wrapping image inside all links
link.appendChild(img);
link.onclick = collapseExpandLink;
collapseLinks[index] = link;
span.appendChild(link);
element.appendChild(span);
}
}
as per my understanding the 1st point you have specified anchor tag with "#" as href so clicking on anchor tag is moving up. so onclick of anchor tag u can return false. so that it wont go up.
Here is an example code I have created for you. I have changed structure little bit to wrap H1 and p tags in a div.
Please have a look here on jsfiddle
Here is working code. I haven't spend time optimizing it but at least will get you going.
$(function() {
$("div > p").hide();
$("h1").each(function() {
var $a = $("<a href='javascript:{}'>Expand</a>")
$a.insertAfter($(this));
$a.click(function() {
var text = $(this).text();
if (text.toLowerCase() == "expand") {
$div = $(this).parent();
$p = $div.find("p");
$p.show();
$(this).text("Collapse");
$(this).parent().get(0).scrollIntoView();
var siblings = $div.siblings()
siblings.find("p").hide();
siblings.find("a").text("Expand");
}else
{
$(this).text("Expand");
$(this).parent().find("p").hide();
}
})
})
})

jQuery check if the div contains such element before appending [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I want to check with jquery if the div contains such element before appending. I tried three versions but none of them helped.
Could you please check the commented lines of my code and help me to find the mistake.
var item = $('<div>');
var info = $(''+abc+'');
item.append(info);
var info = $(''+abc+'');
if (!item.contains(info)) { // first version
if (!item.has(info)) { // second version
if (!item.find(info).length() > 0) { // third version
item.append(info);
}
You can find all <a>'s in <div>'s:
var items = $('div a');
Now, if you need just <a>:
if (items == null) { $('div').append('<a></a>'); }
else, if you want find exact <a>, make a for loop:
var exactHref = "http://...";
if (items == null) {
var dummy = 0;
for (i = 0; i < items.length; i++) {
if (items[i].href == exactHref)
{
dummy +=1;
}
}
if(dummy > 0)
{
$('div').append('<a></a>');
}
}
It's not beautiful, but should work.
You can do it like following:
if (item.find('a').length == 0) {
// do your task here
}
You have to use .contains () for that.
var item=$("<div></div>");
var info = $("<a href=''></a>");
item.append (info);
if (item.contains (info))
{
//your code
item.append (info);
}

Show an individual part of a string as output [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This is my JavaScript code. I want to get only the value inside li tags using JavaScript. How can I do it?
JavaScript
var s="<div><li>First LI</li><li>Second LI</li></div>";
I want to show First li and Second li as output. Thank you.
You can use .text() to get the text content of your li elements:
var text = $(s).find('li').text();
Fiddle Demo
With the help of jQuery it is rather easy:
var str = '<div><li>First LI</li><li>Second LI</li></div>',
first = $('li:eq(0)', str).text(), // "First LI"
second = $('li:eq(1)', str).text(); // "Second LI"
console.log(first, second);
You can use following javascript, get element by tag name and iterate over the values like below
var liArray = document.getElementsByTagName('li');
for(var i=0; i < liArray.length ;i++)
{
var liValue = liArray[i].innerHTML;
alert(liValue);
}
check here, this may help you
<div><li>First LI</li><li>Second LI</li></div>
$('.btn').click(function(){
alert($('div li').text());
});
http://jsfiddle.net/Sathisa/78ktD/
The following code will output: 'First LI Second LI', the contents of both lis separated by a whitespace.
If you need it as array, just omit the join at the end.
var lisContent = $.map(
$('li', "<div><li>First LI</li><li>Second LI</li></div>"),
function(element) {
return $(element).text();
}
).join(' ');
console.log(lisContent);
http://jsfiddle.net/6gG3k/

Down Slider from the list [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am a newbie on Appcelerator Titanium and practicing by developing some mobile apps and came across a situation and need some help.
I have a list of items, which displays from a table and on clicking any item, there should be a bigger space below slides down from clicked item for some entry fields. I am attaching a sample, basically from fig 1, when touched (ofcourse in mobile) it should expand like in fig 2.
Thanks.
This is a bit tricky with Titanum. As it looks it's a row-based approach. So first you should decide to use a TableView
var tableView = Ti.UI.createTableView({
width: Ti.UI.FILL,
height: Ti.UI.FILL,
});
Then you need to add the rows from the left screen. These are simple rows.
var rows = [];
for (var i = 0; i<data.length; i++) {
var row = Ti.UI.createTableViewRow(...);
// do some layout, add some views here
rows.push(row);
}
// add to table view
tableView.data = [rows];
Then you need to apply a 'click' listener.
var isOpen = false; // is already one element clicked and opened?
var whichIsOpen = undefined; // if yes, which one (index of clicked element)?
tableView.addEventListener('click', function(e){
if(isOpen && e.index === whichIsOpen) {
tableView.deleteRow(whichIsOpen+1);
isOpen = false;
return;
}
if(isOpen && e.index === whichIsOpen + 1) {
return;
}
tableView.deleteRow(whichIsOpen+1);
var specialRow = Ti.UI.createTableViewRow(...); // row which contains the elements of the right screen
var newIndex = e.index > whichIsOpen ? e.index : e.index + 1; // because removed one
tableView.insertRowAfter(newIndex-1, specialRow);
whichIsOpen = newIndex;
})
In this solution you can only open one element at the same time. I typed this from my head, i didn't test. So it's up to you!

getting td value per tr [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have code in the following style :
<tr id="201461">
<td id="0A" style="cursor:pointer" onClick = "ProcessTextBoxClick()" value="Feb 23 2008">Feb 23 2008</td>
<td id="0B" style="cursor:pointer" onClick = "ProcessTextBoxClick()" value="Feb 25 2008">Feb 25 2008</td>
<td id="0C" style="cursor:pointer" onClick = "ProcessTextBoxClick()" value="Feb 28 2008">Feb 28 2008</td></tr><tr id="201460">
<td id="1A" style="cursor:pointer" onClick = "ProcessTextBoxClick()" value="47">47</td></tr>
I have some JQuery where I am getting the id of each row, and now I want to get each value in each td for each row. How do I do this?
var tbl = document.getElementById("tbl-1");
var numRows = tbl.rows.length;
for (var i = 1; i < numRows; i++) {
var ID = tbl.rows[i].id;
Your code does not look like jQuery. Are you sure you aren't using the term jQuery as a synonym to JavaScript? :) If that is the case, I suggest you read this question as well; it will make things a lot more clear for you.
Anyway, here goes JavaScript:
var tbl = document.getElementById("tbl-1");
var numRows = tbl.rows.length;
for (var i = 1; i < numRows; i++) {
var ID = tbl.rows[i].id;
var cells = tbl.rows[i].getElementsByTagName('td');
for (var ic=0,it=cells.length;ic<it;ic++) {
// alert the table cell contents
// you probably do not want to do this, but let's just make
// it SUPER-obvious that it works :)
alert(cells[ic].innerHTML);
}
}
Alternatively, if you really use jQuery:
var table = $('#tbl-1').
var rowIds = [];
var cells = [];
$('tr', table).each(function() {
rowIds.push($(this).attr('id'));
$('td', $(this)).each(function() {
cells.push($(this).html());
});
});
// you now have all row ids stores in the array 'rowIds'
// and have all the cell contents stored in 'cells'
in jQuery:
$("table#tbl-1 tr").each(function( i ) {
$("td", this).each(function( j ) {
console.log("".concat("row: ", i, ", col: ", j, ", value: ", $(this).text()));
});
});
You can check it in work here: http://jsfiddle.net/3kWNh/
I want to get each value in each td for each row
Do you want the value of the value attribute, the HTML, or the HTML stripped of markup? The various answers so far have mostly gone with "the HTML", at least one went with "the HTML stripped of markup", but none (so far) has gone with "the value of the value attribute". So:
Using jQuery:
var valuesByRowID = {};
$("#tbl-1 tr").each(function() {
valuesByRowID[this.id] = $(this).find("> td").map(function() {
// Option 1: Getting the value of the `value` attribute:
return this.getAttribute("value"); // or return $(this).attr("value");
// Option 2: Getting the HTML of the `td`:
return this.innerHTML;
// Option 3: Getting the HTML of the `td` with markup stripped:
return $(this).text();
}).get();
});
The end result is an object with properties for each row, with the property name being the row's id value, and the property value being an array of the td information.
So for instance, to get the array for row 201461, you can do this:
var data = valuesByRowID["201461"]; // Note that property names are strings
var index;
for (index = 0; index < data.length; ++index) {
alert(data[index]);
}
The above uses:
$() to find the rows in the table.
map (followed by get) to build the array of values.
A simple JavaScript object to hold the result. JavaScript objects are, at heart, maps (aka dictionaries, aka associative arrays, aka name/value pair collections).
Off-topic:
As I mentioned in a comment on the question, the HTML you've listed there is "invalid" in W3C terminology, td elements don't have a value attribute. You might consider using data-* attributes instead.
As Spudley pointed out in a comment on the question, those id values are likely to cause you trouble. Recommend not having id values that start with a digit. Although valid in HTML5, they're not valid in earlier versions of HTML and not valid in CSS. Since jQuery uses CSS selectors, if you're using CSS, I would strongly advise sticking to the CSS rules. (In your case, it's really easy: Just put an d on the front of them or seomthing.)
You can simply do
$("td","#tbl-1").each(function(){
//access the value as
$(this).html()
});
What you are using there is not jQuery, if you are using jQuery you can use .html(); to retrieve the value.
Here is your code with jQuery:
$('#tbl-1 td').each(function(){
var ID = $(this).attr('id');
var value = $(this).html();
});
If you want to loop over all <td>
$('#tbl-1 td').each(function() {
// do stuff for each td in here...
alert($(this).html());
})
NOTE: This is jQuery whereas your example is native JavaScript.

Categories