使用JavaScript按标题选择元素并进行修改? [英] Select an element by title with JavaScript and modify it?

查看:122
本文介绍了使用JavaScript按标题选择元素并进行修改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要按标题修改元素,如

I need to modify an element by title, as in

javascript: (function () {
  document.body.innerHTML += `<style>* {
    background:% 20#000 % 20!important;
    color:% 20#0f0 % 20!important;
    outline:% 20solid % 20#f00 % 201px % 20!important;
  } </style > `;
})();

我需要更改代码,以便在运行它时(我将其保存在书签栏上的按钮中,以便于访问),它会更改文档中某个元素的位置.

I need to change that code so when I run it (I have it in a button on my bookmarks bar for easier access) it changes the position of a certain element on the document.

我唯一可以选择此元素的方法是通过其title属性,因此我需要找到一种方法来使用javascript通过标题选择元素,然后对其样式进行更改,就像"Ghost CSS"技巧.

The only way I could select this element is by its title attribute, so I need to find a way to select an element by title with javascript and then apply a change to its style, same as that "Ghost CSS" trick.

推荐答案

CSS选择器

使用选择器表示法通过其属性查找节点

Use the selector notation for finding a node by it's attribute

[title="element title attribute value"]


使用 JavaScript


Using JavaScript

与CSS中的选择器相同,但是您可以使用Node . querySelector"rel =" noreferrer> document.querySelector ,或者如果期望多个 Nodes ,则通过

Same selector as in CSS, but you can get the Node using document.querySelector, or if expecting multiple Nodes, a NodeList via document.querySelectorAll

var node = document.querySelector('[title="element title attribute value"]');


执行.innerHTML时,将在调用它的节点中重新解析所有 HTML ,这实际上可能会破坏网页的各个部分.您应该使用 DOM方法创建节点.例如


When you do .innerHTML, you are causing a re-parse of all HTML in the node you've called it on and this can literally destroy sections of web pages. You should use DOM methods for creating nodes, instead. e.g.

var style = document.createElement('style');
style.appendChild(document.createTextNode('div {border: 1px solid red}'));
document.body.appendChild(style);


JavaScript 转换为小书签很简单


Converting JavaScript into a bookmarklet is as simple as

bookmarklet = 'javascript:'
    + encodeURIComponent('(function () {' + code + '}())')
    + ';';

> 这里是一个小提琴 ,您可以在其中粘贴代码

Here is a fiddle where you can just paste in code

这篇关于使用JavaScript按标题选择元素并进行修改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆