Checking an <a> elements text value against a string - javascript

I really need your help with coding this for me. How can I check an <a>'s text element against a string value to see if the tab already exists or not?
I apologize in advance as I am new to this and I am not sure how to accomplish this. An answer using jQuery is fine as well.
var x = "tabTwo"
Some new function here to check and see if the string value tabTwo matches any of the existing tab text values, return true or false.
Here is the HTML markup/structure:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<ul class="tabs">
<li><a href='#tab1'>tabOne</a></li>
<li><a href='#tab2'>tabTwo</a></li>
<li><a href='#tab3'>tabThree</a></li>
<li><a href='#tab4'>tabFour</a></li>
</ul>
</body>
</html>

You can target the a element with jQuery by giving it a class or id and targeting it like so.
$('#tab1');
And then you can get the value using .text() (or many other options)
$('#tab1').text();
And then you can compare it.
if ($('#tab1').text() === x) {
// Do stuff
}
You can further abstract this by assigning all the a tags a shared class and looping through them, and targeting using $(this).
$('.tab_link').each(function(){
if ($(this).text() === x) {
// Do stuff
}
});

I am not sure that understood your problem, but I'll provide you 2 solutions.
1) If you want to check using the id
function isTabExistsById(id) {
return $('.tabs a[href="#'+id+'"]').length > 0;
}
console.log(isTabExistsById('tab1')); // true
console.log(isTabExistsById('tab3')); // true
console.log(isTabExistsById('tabFour')); // false
console.log(isTabExistsById('tab5')); // false
<!DOCTYPE html>
<html>
<head></head>
<body>
<ul class="tabs">
<li><a href='#tab1'>tabOne</a></li>
<li><a href='#tab2'>tabTwo</a></li>
<li><a href='#tab3'>tabThree</a></li>
<li><a href='#tab4'>tabFour</a></li>
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</body>
</html>
2) If you want to check using the content
function isTabExistsByCaption(text) {
var result = false;
$('.tabs a').each(function() {
if ($(this).text().trim() == text) {
result = true;
return;
}
});
return result;
}
console.log(isTabExistsByCaption('tabOne')); // true
console.log(isTabExistsByCaption('tabFour')); // true
console.log(isTabExistsByCaption('tabFive')); // false
console.log(isTabExistsByCaption('tab3')); // false
<!DOCTYPE html>
<html>
<head></head>
<body>
<ul class="tabs">
<li><a href='#tab1'>tabOne</a></li>
<li><a href='#tab2'>tabTwo</a></li>
<li><a href='#tab3'>tabThree</a></li>
<li><a href='#tab4'>tabFour</a></li>
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</body>
</html>
Hope, I understood your problem. If no, could you explain it with more details, please?

Add a class to the a tag and then you can try :
var link = $('.link').text();
if(link == "some Value")
...

You could give a unique class attribute for you 'a' tags. and select the 'a' using jquery like this
$('.classname').each(function(){
if($(this).text() == 'tabTwo' { //here you have it
}
})

var match = "tabTwo"
var tabArray = document.querySelectorAll('li>a');
tabArray.forEach((elem)=>{
if(match === elem.innerText){
return true;
}
return false
});

At first, you have to get all <a> elements using $("a") and iterate through them via .each(function() {...}. Inside the loop, you have to check, does the text() of current element equal to needed string: if it is - then we change tabExists variable from false to true. In my example I have written separate function, so you can invoke it with any parameter you like. I have called checkTabExistence("tabTwo") which should log true and checkTabExistence("tabSix") which should log false:
$(document).ready(function() {
checkTabExistence("tabTwo");
checkTabExistence("tabSix");
});
function checkTabExistence(stringToCheck) {
var tabExists = false;
$("a").each(function() {
if($(this).text() === stringToCheck) {
tabExists = true;
}
});
console.log(stringToCheck + " exists: " + tabExists);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="tabs">
<li><a href='#tab1'>tabOne</a></li>
<li><a href='#tab2'>tabTwo</a></li>
<li><a href='#tab3'>tabThree</a></li>
<li><a href='#tab4'>tabFour</a></li>
</ul>

Related

Change href of <a> element using javascript

Please, code to change domain in href (html, JavaScript).
Exemple:
<a id="NewL" href="http://exemple.com/indice.html">Indice</a>
To:
<a id="NewL" href="http://exemple.net/indice.html">Indice</a>
Exemple code not working:
<script type = "text/javascript" >
function replace() {
var aEls = document.getElementById('NewL').getElementsByTagName('a');
aEls.href = aEls.href.replace('http://exemple\.com', 'http://exemple\.net');
}
</script>
Thanks, #t.niese:
<a id="NewL" href="http://exemple.com/indice.html">Indice</a>
<script type="text/javascript" >
function replace() {
var aEl = document.getElementById('NewL');
aEl.href = aEl.href.replace('http://exemple.com', 'http://exemple.net');
}
replace();
</script>
Please help me, not change in various ID in same page:
<a id="NewL" href="http://exemple.com/indice.html">Indice</a>
<a id="NewL" href="http://exemple.com/indice2.html">Indice 2</a>
<script type="text/javascript" >
function replace() {
var aEl = document.getElementById('NewL');
aEl.href = aEl.href.replace('http://exemple.com', 'http://exemple.net');
}
replace();
</script>
Element.getElementsByTagName():
[...]The subtree underneath the specified element is searched, excluding the element itself.[...]
so you search for the elements with the tag name a within your element with the id NewL
Because document.getElementById('NewL') is already your a element, you won't need the getElementsByTagName('a'), as of that you should only write:
var aEl = document.getElementById('NewL');
Also your replace is wrong, you don't need to escape the . if you pass the search as string.
aEl.href = aEl.href.replace('htp://exemple.com', 'htp://exemple.net');
Beside that Element.getElementsByTagName() returns a list of elements, so even if your search would have been correct, you would need to use a loop to iterate through that result.
change your javascript to the following:
<script type = "text/javascript" >
function replace() {
var aEl = document.getElementById('NewL');
aEl.href = aEl.href.replace('htp://exemple\.com', 'htp://exemple\.net');
}
</script>
You already selected the element by the getElementById no need to find the a class in it. Also you mispelled the variable which I changed to aEl

Handlebar custom helper stuck on "doesn't match each"

I want to make certain elements lowercase by using handlebars (I know it's possible with CSS, but you can't do that for classnames for example). Anyhow, I am getting this error:
Uncaught Error: toLowerCase doesn't match each
My code:
<script id="icon-template" type="text/x-handlebars-template">
{{#each results}}
<li>
<div class="content">
<i class="Icon icon-{{#toLowerCase contentType}}"></i>
</div>
</li>
{{/each}}
</script>
Custom helper:
<script type="text/javascript">
Handlebars.registerHelper("toLowerCase", function(input) {
var output = input.toLowerCase();
return output.replace(" ", "");
});
</script>
What am I doing wrong?
I figured it out. For anyone having the same problems:
<script type="text/javascript">
handlebars.registerHelper("toLowerCase", function(input) {
var output = input.toLowerCase();
return output.replace(" ", "");
});
</script>
Handlebars must have a lowercase letter (like this: handlebars) at first & no hashtag is needed when you are using a custom helper. So the custom helper is now toLowerCase instead of #toLowerCase
<script id="icon-template" type="text/x-handlebars-template">
{{#each results}}
<li>
<div class="content">
<i class="Icon icon-{{toLowerCase contentType}}"></i>
</div>
</li>
{{/each}}
</script>
If a handlebars helper name is all lowercase:
<script type="text/javascript">
handlebars.registerHelper("lower", function(input) {
var output = input.toLowerCase();
return output.replace(" ", "");
});
</script>
you will need to use the hash when invoking it:
<script id="icon-template" type="text/x-handlebars-template">
<i class="Icon icon-{{#lower contentType}}"></i>
</script>
If the helper uses a CamelCase name:
<script type="text/javascript">
handlebars.registerHelper("toLowerCase", function(input) {
var output = input.toLowerCase();
return output.replace(" ", "");
});
</script>
then you do not use the hash:
<script id="icon-template" type="text/x-handlebars-template">
<i class="Icon icon-{{toLowerCase contentType}}"></i>
</script>
It matters how you invoke the helper. If you use a hash(#) then it's considered a Block Helper and needs to be closed. Otherwise you'll get that parsing error.
{{#toLowerCase}}Some UPPERCASE text{{/toLowerCase}}
Obviously it also matters what the helper code does. The syntax above is correct but the code may not have the desired effect.

Turning an array into a nested list

Pretty new to Angular, and I'm trying to do a sort of unconventional operation.
Say I have an array like this: ["A","B","C","D","E","F","G"];
I want to output HTML like this:
<ul>
<li>A</li>
<ul>
<li>B</li>
<ul>
<li>C</li>
<ul>
<li>D</li>
<ul>
<li>E</li>
<ul>
<li>F</li>
<ul>
<li>G</li>
</ul>
</ul>
</ul>
</ul>
</ul>
</ul>
</ul>
Essentially, I just want to keep nesting until I hit the end of the array. I'm having trouble figuring out how to do this. I don't have any code examples, unfortunately, because I'm having trouble how to do this without freezing the browser inside a while loop.
Nevertheless, here's what I've got:
<div class="trail" ng-include="'trail'"></div>
<script type="text/ng-template" id="trail">
<li>{{trailItem.content}}<li>
<ul ng-repeat="trailItem in post.trail" ng-include="'trail'">
</ul>
</script>
The above is meant to work with a data structure where post is an array of objects, of which content is a property.
However, this loops forever, and the browser freezes.
var ary = ["A", "B", "C", "D", "E", "F", "G"];
var $container = $('<div></div>');
var dom = $container;
for (var i = 0; i < ary.length; i++) {
dom = appendDom(dom, ary[i]);
}
function appendDom(dom, value) {
var $ul = $('<ul><li>' + value + '</li></ul>');
$(dom).append($ul);
return $ul;
}
alert($container.html());
The output is your need
I couldn't get it to work exactly with the one dimensional array like you posted but I did find a really good example with a jsfiddle at http://benfoster.io/blog/angularjs-recursive-templates
Also, here is what I have so far:
http://jsfiddle.net/haydenk/s19v2f1m/3/
<div ng-controller="MainCtrl">
<script type="text/ng-template" id="awesomeTree">
{{ awesomeThing }}
<ul ng-if="awesomeThings">
<li ng-repeat="awesomeThing in awesomeThings" ng-include="'awesomeTree'"></li>
</ul>
</script>
<ul>
<li ng-repeat="awesomeThing in awesomeThings" ng-include="'awesomeTree'"></li>
</ul>
</div>
var app = angular.module('testApp',['ngAnimate']);
app.controller('MainCtrl', function ($scope) {
$scope.awesomeThings = ['A','B','C','D','E','F','G','H'];
});
try this one .
HTML :
<div ng-controller="testCtrl">
<div add-ul-li arr-list-val=arrList>
</div>
</div>
JS :
app.controller("testCtrl",function($scope){
$scope.arrList = ["A","B","C","D","E","F","G"];
})
.directive("addUlLi",function(){
var finalHtml="";
return {
scope : {arrListVal: '='},
link: function(scope,ele,attr){
scope.arrListVal.reverse();
angular.forEach(scope.arrListVal,function(oneElement,key){
console.log(key)
if(key==0){
finalHtml = "<ul> <li>"+oneElement+"</li> </ul>";
}else{
finalHtml = "<ul> <li>"+oneElement+" "+finalHtml+"</li> </ul>";
}
if((key+1)==scope.arrListVal.length){
ele.append(finalHtml);
}
})
}
}
})
Check this plunker

Creating Inline Style Sheet With Javascript

Hihi. I'm trying to create an inline style sheet at the beginning of the page which reacts to what i'm GETTING from the url. Im doing this so I can have the navbutton of the page that im on highlighted. Kind of like here, www.myeg.net , but they have a static site and it is much easier.
<script type="text/javascript">
function parseUrl( url ) {
var a = document.createElement('a');
a.href = url;
return a;
}
var page=parseUrl('').search
function getSecondPart(str) {
return str.split('=')[1];
}
var site=getSecondPart(page);
var style = document.createElement("style");
style.innerHTML = ".nav_" + page + " { background-image:url('images/gradients/transparent_gradient.png');}";
document.body.appendChild(style);
}
</script>
</head>
<body>
<center><div><img width="960px" height="187.5" src="images/fullbanner.png"></div></center>
<div id="wrapper">
<div id="navbar">
<ul>
<li class="nav_index">Home</li>
<li class="nav_archive">News</li>
<li class="nav_squads">Roster</li>
<li class="nav_forum">Forums</li>
<li class="nav_about">Contact</li>
</ul>
I'm pretty noob at javascript so sorry ;;;
Try this:
<style type="text/css">
#banner{text-align:center;}
#banner>img{width:960px;height:187.5px;}
#nav>.selected{background-image:url('images/gradients/transparent_gradient.png');}
</style>
</head>
<body>
<div id="banner"><img src="images/fullbanner.png"></div>
<div id="wrapper">
<div id="navbar">
<ul id="nav">
<li id="nav_index">Home</li>
<li id="nav_archive">News</li>
<li id="nav_squads">Roster</li>
<li id="nav_forum">Forums</li>
<li id="nav_about">Contact</li>
</ul>
<script type="text/javascript">
document.getElementById('nav_'+window.location.href.split('=')[1]).className='selected';
</script>
You shouldn't use <center>, it's deprecated!
Instead of writing a style sheet with javascript in order to match an element, you should match a class and then only add that class to your element with javascript.
And I don't understand very well your code:
function parseUrl( url ) {
var a = document.createElement('a');
a.href = url;
return a;
}
var page=parseUrl('').search
It gives "" to me, but I have never seen .search on an anchor... If you want to get the current URL, you can do window.location.href.
And another point: if you use var outside functions (in global scope) you are creating a global variable, which won't be deleted and uses memory. Then, you can remove it when you don't want to use it anymore (var a="dagjhdjgailghkagh";/*code*/;a=null;), or use a self-execute function (closure) which contains your code.
Edit:
Sorry, instead of #nav>selected I meant #nav>.selected.
You can see a demo here: http://jsfiddle.net/VhWHp/
(But the url doesn't have =, so I replace it manually to 'archive'. In your site, remove that line)
And yes, it loads CSS first and then the nav. But that's the true power of CSS and javascript: if you set a class to an element after it has been loaded, that element will have the styles applied to that class.
Edit 2:
The problem is that if you do split('=')[1], the result will be something like "news&action" instead of "news".
Then, you could use a function I wrote some time ago:
function sQuery(arg) {
if(window.location.search){
var que = window.location.search.substring(1);
if(arg=='string'){return que;}
que = que.split("&");
if(!arg||arg=='array'){return que;}
for(var i=0;i<que.length;i++){
var qvar = que[i].split("=");
if(qvar[0]==arg){
return qvar[1];
}
}
}
return false;
}
Then, call the function like this: sQuery('site')
document.getElementById('nav_'+(sQuery('site')||'index')).className='selected';
You can also call sQuery('array') or just sQuery() if you want to get ["site=news","action=archive"], and sQuery('string') if you want "site=news&action=archive". If you won't use that, you can simplify the function:
function sQuery(arg) {
if(window.location.search){
var que = window.location.search.substring(1).split("&");
for(var i=0;i<que.length;i++){
var qvar = que[i].split("=");
if(qvar[0]==arg){
return qvar[1];
}
}
}
return false;
}

How to change the innerHTML of a div in the main page according to the div value in the included page?

I have included a file named test.php in the file index.php
lets assume index.php is like this
<html>
<head>
</head>
<body>
<h1 id="dash">Index</h1>
<div id='tab.php'>
<?php include('tab.php'); ?>
</div>
</body>
</html>
and tab.php is like this
<html>
<head>
</head>
<body>
<ul>
<li id='date' onClick="change_head(this.id);">Dates</li>
<li id='appoint' onClick="change_head(this.id);">Appointments</li>
<ul>
</body>
</html>
Here what i would like to do is, if the list item date is clicked(list items are actually tabs). The inner html of the h1 tag with id dash should be changed to Dates and if the list item appoint is clicked the inner html of same h1 tag with id dash should change to appointments.
how can i do that ?? i tried the usual javascript way by taking the ids and applying the if condition to change the innerHTML but it was not working..anyone pls help me how to do it
JAVASCRIPT (this is the js i tried to achive it...i added this in index.php)
function change_head(id){
dash = document.getElementById('dash').innerHTML;
if(id == date){
dash = "Date";
}
else if(id == appoint){
dash = "Appointment";
}
else{
dash = "Index";
}
}
You could try using jquery... something like this:
<script type="text/javascript">
$(document).ready(function () {
$("li#date").click(function () {
$("h1#dash").val("Dates");
});
$("li#appoint").click(function () {
$("h1#dash").val("Appointments");
});
});
</script>
Of course, if you had more of these tabs, I would create a single click event handler for all "li" elements and switch on the ID :-)
Assuming you're new to jquery, you'd also have to include the jquery script in your page. Something like:
<script src="/Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
Check out jquery.com to get started.
If you want do it with JavaScript (i.e. without page reloading), so you need use DOM innerHTML.
Something like (if you didn't use jQuery), didn't test this code through, hope you get idea:
var changetext = function(e,t) {
e.innerHTML = t;
},
elemheader = document.getElementById('dash'),
elemdate = document.getElementById('date'),
elemappoint = document.getElementById('appoint');
if (elemdate.addEventListener) {
elemdate.addEventListener('click',changetext(elemheader,'Date'),false);
}
if (elemappoint.addEventListener) {
elemappoint.addEventListener('click',changetext(elemheader,'Appoint'),false);
}

Categories

Resources